【发布时间】:2014-04-15 11:44:29
【问题描述】:
我想在我的系统后端创建一个用户表单来创建用户。 我使用具有“角色”字段的实体作为类型数组 我想使用带有该实体字段的选择字段类型表单。 我使用转换器类系统在实体和表单之间转换数据。
但我在脑海中转过身来,什么都没有正确运行。
当我使用选择类型的选项“多个”时,我的字段会正确显示,但我不想为此字段显示和选择多个值。
我有Notice: Undefined offset: 0 错误
要么
我有ContextErrorException: Notice: Array to string conversion
这里有一些基本代码:
用户窗体类
$builder->add($builder->create('roles', 'choice', array(
'label' => 'I am:',
'mapped' => true,
'expanded' => false,
'multiple' => false,
'choices' => array(
'ROLE_NORMAL' => 'Standard',
'ROLE_VIP' => 'VIP',
)
))->addModelTransformer($transformer));
变压器类
class StringToArrayTransformer implements DataTransformerInterface
{
public function transform($array)
{
return $array[0];
}
public function reverseTransform($string)
{
return array($string);
}
}
控制器方法
$user = new User(); //init entity
$form = $this->createForm(new UserForm(), $user);
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$em->persist($form);
$em->flush();
return $this->redirect($this->generateUrl('task_success'));
}
实体部分
/**
* @ORM\Column(name="roles", type="array")
*/
protected $roles;
public function getRoles()
{
return $this->roles;
}
public function setRoles(array $roles)
{
$this->roles = $roles;
return $this;
}
我的字段角色实体必须是一个数组才能正确运行安全组件 Symfony
你能帮我理解为什么这个字段表单拒绝显示吗?
我已经阅读了同一问题中的其他问题,但有任何我不明白的地方,因为没有任何东西可以帮助我解决我的问题。
如果你能帮助我了解我的特殊情况...
感谢支持
【问题讨论】:
-
如果不想多选,为什么你的role属性是array类型的?
-
因为安全 symfony 组件集成
标签: forms symfony doctrine-orm