Symfony FormType PropertyAccessor.php错误

时间:2016-02-10 08:22:14

标签: php symfony

使用formType将数据保存到具有多对多关系的模型时,出现错误。

错误是

  

捕获致命错误:传递给AppBundle \ Entity \ User :: removeRole()的参数1必须是AppBundle \ Entity \ Role的实例,给定字符串,在/ Code / project / vendor / symfony / symfony / src /中调用第616行的Symfony / Component / PropertyAccess / PropertyAccessor.php并定义了

将Role模型注入表单的最佳方法是什么?

该模型具有以下内容:

/**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
 * @ORM\JoinTable(name="user_roles")
 */
private $roles;

/**
 * Remove role
 *
 * @param Role $role
 */
public function removeRole(Role $role)
{
    $this->roles->removeElement($role);
}

/**
 * Add role
 *
 * @param Role $role
 *
 * @return User
 */
public function addRole(Role $role)
{
    $this->roles[] = $role;

    return $this;
}

角色反向

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

要将数据保存在控制器中,我有

    $user = new User();
    $form = $this->createForm(UserType::class, $user);
    $form->handleRequest($request);
    if( $form->isSubmitted() && $form->isValid() ){

        $encryptedPassword = $this->get('security.password_encoder')
            ->encodePassword($user, $user->getPlainPassword());
        $user->setPassword($encryptedPassword);

        $em = $this->getDoctrine()->getManager();
        $em->persist($user);
        $em->flush();
        return $this->redirect($this->generateUrl('user_list'));
    }
    return $this->render('user/new.html.twig', array('form' => $form->createView()));

FormType有

class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('name')
        ->add('email')
        ->add('username')
        ->add('plainPassword', RepeatedType::class, array(
            'type' => PasswordType::class,
            'invalid_message' => 'The password fields must match.',
            'options' => array('attr' => array('class' => 'password-field')),
            'required' => true,
            'first_options'  => array('label' => 'Password'),
            'second_options' => array('label' => 'Repeat Password'),
        ))
        ->add('roles', EntityType::class, array(
            'class' => 'AppBundle:Role',
            'choice_label' => 'name',
            'multiple'    => true
        ));
}

public function configureOptions(OptionsResolver $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'AppBundle\Entity\User'
    ));
}

}

1 个答案:

答案 0 :(得分:0)

我已经解决了问题,问题是并且可能会导致其他人一样。

这是因为:

class User implements UserInterface

需要

/**
 * @return mixed
 */
public function getRoles()
{
    return ARRAY|STRING;
}

为了解决这个问题,我创建了:

/**
 * @ORM\ManyToMany(targetEntity="Role", inversedBy="users")
 * @ORM\JoinTable(name="user_roles")
 */
private $userRoles;

然后一切都来自getUserRoles并且工作正常。