我正在创建一个使用实体类型的表单。 实体表单类型将Roles显示为复选框列表。 但我不知道如何设置默认值。我需要从DB获取默认值,然后动态检查其中一些选项。
根据文档,似乎'preferred_choices'选项不会完成这项工作。
有人可以帮助我吗?
如果有些句子没有意义,请抱歉我的英语。
3表:
的UserRole
+---------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| user_id | int(11) | YES | MUL | NULL | |
| role_id | int(11) | YES | MUL | NULL | |
+---------+---------+------+-----+---------+----------------+
ADMINUSER
+-----------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| username | varchar(25) | NO | UNI | NULL | |
| salt | varchar(32) | NO | | NULL | |
| password | varchar(40) | NO | | NULL | |
| email | varchar(60) | NO | UNI | NULL | |
| is_active | tinyint(1) | NO | | NULL | |
+-----------+-------------+------+-----+---------+----------------+
作用
+-------+-------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(50) | NO | UNI | NULL | |
+-------+-------------+------+-----+---------+----------------+
表单构建器:
$builder->add('role', 'entity', array(
'class' => 'AcmeAdminBundle:Role',
'property' => 'name',
'multiple' => TRUE,
'expanded' => TRUE,
));
答案 0 :(得分:0)
您必须在User和Role之间定义ManyToMany关系,在User实体上使用一些传统方法:setRoles,getRoles,addRole ...
将在您的表单中加载的数据来自用户实例的数据,例如$ user。
$user = new User; // or $user is existing User, same logic
$rolesYouWantToSetToUser = array('ROLE_1', 'ROLE_2', 'ROLE_3');
foreach ($rolesYouWantToSetToUser as $roleId) {
// $em must previsouly be set as EntityManager in your code
$role = $em->getReference('YourBundle:Role', $roleId);
$user->addRole($role);
}
// From a controller
$form = $this->createFormBuilder($user)
->add('roles', 'entity', array(
'class' => 'AcmeAdminBundle:Role',
'multiple' => true,
'expanded' => true,
'property' => 'name',
))
->getForm();