Symfony2选择:期望类型为“标量",“数组"的自变量.给定 [英] Symfony2 Choice : Expected argument of type "scalar", "array" given

查看:93
本文介绍了Symfony2选择:期望类型为“标量",“数组"的自变量.给定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作一个带有选择列表的表格.这是我的FormType的内容(仅作为测试):

I'm making a form with a choice list. Here's the content of my FormType (only as a test):

$builder->add('regionUser');
$builder->add('roles' ,'choice' ,array('choices' => array(
        "ROLE_ADMIN" => "ROLE_ADMIN",
            "ROLE_USER" => "ROLE_USER",
        ),
        'required'  => true,
        'multiple' => false,
));

执行此操作时,出现以下错误:

When I execute this, I get the following error:

类型为标量",数组"的预期参数

Expected argument of type "scalar", "array" given

出了什么问题?该怎么解决?

What goes wrong? How to solve it?

推荐答案

有3种解决方案:

  1. 使用多项选择字段来显示角色字段.多种的 选择返回一个数组.

  1. Use a multiple choices field to show the roles field. Multiple choices returns a array.

在您的表单中,不要显示角色"字段. 仅在您的构建表单中而不是您的实体中放置一个新字段角色". (如果需要,可以使用角色层次结构自动填充它). 在onSuccess方法中,获取角色"以为您的用户设置角色.

In your form, don't show the "roles" field. Put a new field "role" only in your buildform, not in your entity. (You can fill autmaticaly it with the role hierarchy if you want). In the onSuccess method, get the "role" to set roles for your user.

$ user-> addRole($ role);

$user->addRole( $role );

  1. 创建用户类时,请勿使用 FOSUserBundle.复制它并更改方法的原型.
  1. When you create your user class, don't use the UserInterface from the FOSUserBundle. Copy it and change the prototype of the method.

//FOSUserBundle/UserInterface

// FOSUserBundle/UserInterface

函数setRoles(array $ roles);

function setRoles(array $roles);

// YourUserBundle/UserInterface 
function setRoles($roles); 

并在您的用户类中更改方法

And change the method in your User Class

// FOSUserBundle/UserInterface 
public function setRoles(array $roles) 
{ 
        $this->roles = array(); 
        foreach ($roles as $role) { 
            $this->addRole($role); 
        } 
} 

// YourUserBundle/UserInterface 
public function setRoles($roles) 
{ 
        if (is_string()) { 
            $this->addRole($roles); 
        } else { 
            $this->roles = array(); 
            foreach ($roles as $role) { 
                $this->addRole($role); 
            } 
        } 
}

您可以在此处找到更多信息: https://groups.google .com/group/symfony2/browse_thread/thread/3dd0d26bcaae4f82/4e091567abe764f9

You can find more information here: https://groups.google.com/group/symfony2/browse_thread/thread/3dd0d26bcaae4f82/4e091567abe764f9

https://github.com/FriendsOfSymfony/FOSUserBundle

这篇关于Symfony2选择:期望类型为“标量",“数组"的自变量.给定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆