symfony2多对多表单复选框 [英] symfony2 many-to-many form checkbox

查看:114
本文介绍了symfony2多对多表单复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在symfony中创建了两个实体:多对多关系中的用户和角色.这意味着每个用户可以拥有更多角色,并且可以将角色设置为多个用户.

I have in symfony created 2 entities: User and Role in many-to-many relationship. That means every user can have more roles and roles can be set to many users.

用户类别:

  /**
   * @ORM\Entity
   * @ORM\Table(name="JEP_User")
   * @ORM\Entity(repositoryClass="Chrchel\JepBundle\Repository\UserRepository")
   */
class User implements AdvancedUserInterface {

/**
 * @ORM\Id()
 * @ORM\Column(name="id",type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @ORM\Column(name="username",type="string",length=100,unique=true)
 */
private $username;

 /**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
 *
 */
protected $roles;

//....
}

角色类别:

/**
 * @ORM\Table(name="JEP_Role")
 * @ORM\Entity()
 */
 class Role implements RoleInterface {

/**
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id()
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

  /** @ORM\Column(name="name", type="string", length=30) */
protected $name;

 /** @ORM\Column(name="role", type="string", length=20, unique=true) */
protected $role;

 /** @ORM\ManyToMany(targetEntity="User", mappedBy="roles") */
protected $users;
 //...
 }

我无法弄清楚如何在Symfony2中组成查询生成器以列出所有存在的角色,并将其添加到UserForm的末尾,可以在其中选择(作为复选框)授予用户的角色. 我试图在UserType中使用这样的集合

I cant figure how to compose query builder in Symfony2 to list all roles that exists and add it to the end of UserForm where can be selected (as checkboxes) roles granted to the user. I tried to use collection like this in UserType

->add('roles', 'collection',array('label' => 'Role', 'required' => false,'type'=> new RoleType()))

我从symfony得到的最好的结果是带有文本框的行,其中包含选定的角色名称.但这不是我所需要的.

The best I get from symfony are rows with textboxes with selected names of roles. But this is not, what I need.

推荐答案

我使用了实体类型而不是集合.我的东西集合主要用于实际上创建一个Role对象并将其分配给User.

I've used entity type instead of collection. I thing collection is mainly used to actually create a Role object and assign it to User.

如果您只想列出所有现有角色并能够选择并将其分配给用户,则:

If you want to just list all existing roles and be able to select and assign it to the user then:

->add('roles', 'entity', array(
    'class' => 'MyBundle:Role',
    'property'     => 'name',
    'multiple'     => true
));

编辑:这会将窗口小部件呈现为多个<select>,请参考

EDIT: this will render the widget as a multiple <select>, refer to entity type to render as checkbox list.

这篇关于symfony2多对多表单复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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