我在 symfony 2 + FOSUserBundle 中创建新/编辑用户表单时遇到问题。我想让管理员从下拉列表或单选按钮列表中选择用户角色,但我似乎无法让它工作。我在这里找到了这个答案How can I pass a full security roles list/hierarchy to a FormType class in Symfony2? 这是我能找到的最相关的事情,但它不起作用。
这是当前的 UserType 表单。我想从容器中获取角色,但如果不引发错误,我似乎也无法让它工作。角色将正确填充下拉列表,但不会显示当前分配的角色,并且不允许更新信息,因为它期望它是一个数组$entity->addRoles(array('ROLE_SUPER_ADMIN'));
,但它只是作为字符串提交。
namespace Wes\AdminBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class UserType extends AbstractType
{
private $roles;
public function __construct($roles) {
$this->roles = $roles;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username')
->add('email')
->add('enabled')
->add('roles', 'choice', array(
'choices' => $this->flattenArray($this->roles),
))
->add('firstName')
->add('lastName')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Wes\AdminBundle\Entity\User',
'roles' => null,
'userRole' => null,
));
}
public function getName()
{
return 'wes_adminbundle_usertype';
}
private function flattenArray(array $data)
{
$returnData = array();
foreach($data as $key => $value)
{
$tempValue = str_replace("ROLE_", '', $key);
$tempValue = ucwords(strtolower(str_replace("_", ' ', $tempValue)));
$returnData[$key] = $tempValue;
}
return $returnData;
}
}
这是控制器。
public function editAction($id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('WesAdminBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$editForm = $this->createForm(new UserType($this->container->getParameter('security.role_hierarchy.roles')), $entity);
$deleteForm = $this->createDeleteForm($id);
return $this->render('WesAdminBundle:User:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
/**
* Edits an existing User entity.
*
*/
public function updateAction(Request $request, $id)
{
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('WesAdminBundle:User')->find($id);
if (!$entity) {
throw $this->createNotFoundException('Unable to find User entity.');
}
$deleteForm = $this->createDeleteForm($id);
$editForm = $this->createForm(new UserType($this->container->getParameter('security.role_hierarchy.roles')), $entity);
$editForm->bind($request);
if ($editForm->isValid()) {
$em->persist($entity);
$em->flush();
return $this->redirect($this->generateUrl('wes_admin_user_edit', array('id' => $id)));
}
return $this->render('WesAdminBundle:User:edit.html.twig', array(
'entity' => $entity,
'edit_form' => $editForm->createView(),
'delete_form' => $deleteForm->createView(),
));
}
我已经为此奋斗了几天,我似乎无法让它正常工作。有什么想法吗?