使用 formType 将数据保存到具有多对多关系的模型中时出现错误。
错误是
将可捕获的致命错误:传递给 AppBundle''Entity''User::removeRole(( 的参数 1 必须是 AppBundle''Entity''Role 的实例,给定字符串,在第 616 行的/Code/project/vendor/symfony/symfony/symfony/Symfony/Component/PropertyAccess/PropertyAccessor.php 中调用并定义
榜样注入表单的最佳方法是什么?
该模型具有以下内容:
/**
* @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()));
并且表单类型具有
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'
));
}
}
我已经
解决了,这个问题是并且可能导致其他人同样的问题。
这是因为:
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并且工作正常。