首页 文章

Symfony 2访问formtype的实体数据

提问于
浏览
1

我正在使用Symfony2创建自己的登录应用程序,我是Symfony的新用户 . 我知道我有FOSUserBundle可供我使用,但我想先自己学习安全 .

我的访问控制定义了3个角色:ROLE_SUPER_ADMIN,ROLE_ADMIN和ROLE_USER . 此外,已定义的角色还具有与其关联的其他角色,例如ROLE_ADMIN_VIEW_USERS

我在 NOT 上使用security.context service on entity.roles来映射我的角色来自实体,因为我只想影响ROLE_ADMIN和ROLE_USER . 注册后,每个用户都被赋予角色ROLE_USER . 当具有ROLE_SUPER_ADMIN的用户查看用户或管理员的编辑页面时,我试图放入一个显示'Make this User an Admin'的复选框 . 如果他们已经在实体getRoles中有ROLE_ADMIN,则将检查该框 .

如果选中此框,我会在操作中执行此操作

if ($editForm->isValid()) {
            $role = ( 'ROLE_ADMIN' === $editForm->get('role')->getViewData())
                    ? "ROLE_ADMIN"
                    : "ROLE_USER";
            $entity->setRoles(array($role));
            $em->flush();

            return $this->redirect($this->generateUrl('admin_new_edit', array('id' => $id)));
        }

所以我的问题是:如果实体中的getRoles()是ROLE_ADMIN,我如何选中框?请记住,如上所述,角色映射在实体中,但角色不是 . 我不想't want to use roles from the mapped entity because there are several values from the security service that I don' .

$builder
        ->add('username', 'text')
        ->add('password', 'password')
        ->add('email', 'email')
        ->add('role', 'choice', array(
            'mapped' => false,
            'label' => 'Make Admin',
            'value' => 'ROLE_ADMIN',
            'required' => false,
            //show following attribute only if entity getRoles is ROLE_ADMIN
            //how do i get the value from the entity?
            'attr' => array('checked'=>'checked'),
            ))

1 回答

  • 0

    我的建议是这样的:

    ->add('role', 'choice', array(
                'mapped' => true,
                'label' => 'Make Admin',
                'multiple' => true,
                'expanded' => true,
                'choices' => array('ROLE_ADMIN' => 'Yes')
                'required' => false,
                ))
    

    如果实体具有名为“roles”的属性,则该值应自动从实体中获取,就像您的其他字段一样 . 您还可以向choices数组添加其他角色,您将获得每个角色的复选框 .

    我没有测试它,但我希望它有效 .

相关问题