1

首先,感谢所有关注这个问题的人。我有一个像 userFormType 这样的 FormType。

class UserFormType extends AbstractType{
    public function buildForm(FormBuilder $builder, array $options)
    {
         $builder->add('address','collection', ....)
                 ->add('group','entity',....)
                 ->add('companies','collection',....);
         ...
    }

}  

所以你看我在用户表单中有两个集合。我创建表格并设置公司。当我只想修改公司和地址的信息,而不是与集团联系时。所以我必须呈现一个用户表单,而不是一些公司表单或地址表单。所以我写了一个这样的控制器:

    $user= $this->get('security.context')->getToken()->getUser();
    $form =$this->createForm(new UserForm(),$user);
    $request = $this->get('request');
    if ('POST' == $request->getMethod()) {
         $form->bindRequest($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($user);
            $em->flush();
            ....
        }

     }

当然,我不想修改组,所以在树枝模板中,我不渲染组。表单正确呈现,但每次我尝试提交时,它都会告诉我:

 Argument 1 passed to ... User->setGroup() must be an instance of Group ... null given

所以我问,我该怎么办?

4

1 回答 1

1

The error specifically is because your method definition in User is probably:

public function setGroup(Group $group);

but in order to set it null it would need to be:

public function setGroup(Group $group = null);

That will fix the error but it still might not be what you want functionality wise. My question is, why have the group field on the form if you are not using it? You may need another form type or pass an option to the form to not include the group field during edits.

于 2012-06-01T15:08:06.707 回答