2012-12-21 43 views
0

這裏是我的形式上市:Symfony2的額外領域FormError與隱藏字段驗證表單

$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」字段 - 一切正常。 我如何使用隱藏類型並進行驗證?

+0

詢問時設置你做了同樣的FormType類還是你綁定到一個實體?如果是後者,可能性是綁定到未定義的屬性(id),或者它是不能以這種方式在窗體中設置的主鍵。 – phpisuber01

+0

我將它綁定到一個實體,但這是未定義的屬性。名稱無關緊要。 – Aronsky

回答

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)) { 

有了這個前檢查的要求,您可以您使用的是獨立形式的頁面