Symfony2 Extra字段使用隐藏字段验证表单时的FormError

时间:2012-12-21 15:20:53

标签: php forms validation symfony

以下是我的表单列表:

$builder = $this->createFormBuilder($project)
                ->add('name','text')
                ->add('type','choice', array(
                    'choices'  => $enumtype
                   ))
                ->add('begindate','date')
                ->add('expecteddate','date')
                ->add('events', 'collection', array(
                    'type' => new EventType(),
                    'allow_add' => true,
                    'allow_delete' => true,
                    'by_reference' => false,
                    ))

                ->add('financial', 'file', array(
                    'property_path' => false,
                    'required' => false
                    ))
                ->add('investition', 'file', array(
                    'property_path' => false,
                    'required' => false
                    ));
if ($defaults) {
    $builder->add('id','hidden',array('data' => $defaults['id'], 'property_path' => false));
    $form = $builder->getForm();
    $form->setData($defaults);
}
else
    $form = $builder->getForm();

当我尝试验证此表单时,我收到FormError对象:

Array ( 
    [0] => Symfony\Component\Form\FormError Object  (
        [messageTemplate:protected] => This form should not contain extra fields.
        [messageParameters:protected] => Array (
            [{{ extra_fields }}] => id 
        )
        [messagePluralization:protected] =>
    )
)

如果我排除“id”字段 - 一切正常。 我如何使用隐藏类型并进行验证?

1 个答案:

答案 0 :(得分:2)

这个问题来自隐藏参数是optionnal。

常见的错误是在提交表单时不设置相关类型。

错误示例:

public function addOrEditAction($id=null)
{
    $request = $this->getRequest();

    if (!$id) {
        $model = new Actu();
        $type  = new ActuType(); /* I do not set the default id on submit */
    } else {
        $em = $this->getDoctrine()->getEntityManager();
        $model = $em->getRepository("MyBundle:Actu")
                    ->find($id);
        if (!$model) {
            return $this->redirect($this->generateUrl('admAddNew'));
        } else {
            $type = new ActuType($model->getId());
        }
    }

    $form = $this->createForm($type,$model);

    if ('POST' == $request->getMethod()) {
        $form->bind($request);
        if ($form->isValid()) {
            $em = $this->getDoctrine()->getEntityManager();
            $em->persist($model);
            $em->flush();

            return $this->redirect($this->generateUrl('admNews'));
        }
    }

    $data = array('form'=>$form->createView());
    return $this->render('MyBundle:Page:news-add.html.twig',$data);
}

致电控制器时
ActuType()包含:

'name', 'content', 'date', 'id'

提交表单时
ActuType()包含:

'name', 'content', 'date'

他们不匹配。
这实际上会返回一个错误,因为在提交表单时会有一个包含要编辑的行的隐藏id的额外字段。

您需要做的就是在初始化FormType

之前检查请求
if (!$id && null === $id = $request->request->get('newsType[id]',null,true)) {

使用此功能,您可以设置在请求页面时所执行的相同FormType

相关问题