2013-04-22 61 views
1

在Zend框架2的應用程序,我在我的控制器的操作方法如下形式:ZF2:「需要」 =>假忽略DateSelect元素

public function testAction() 
{ 
    $form = new \Zend\Form\Form('test'); 

    $date = new \Zend\Form\Element\DateSelect('date'); 
    $date->setOptions(array(
      'label' => 'Date', 
      'min_year' => date('Y') - 10, 
      'max_year' => date('Y') + 10, 
     ) 
    ); 

    $date->getDayElement()->setEmptyOption('day'); 
    $date->getMonthElement()->setEmptyOption('month'); 
    $date->getYearElement()->setEmptyOption('year'); 

    $form->add($date); 

    $form->add(array(
     'name' => 'submit', 
     'attributes' => array(
      'type' => 'submit', 
      'value' => 'submit', 
      'id' => 'submitbutton', 
     ), 
    )); 

    if ($this->request->isPost()) { 
     $data = $this->request->getPost();    
     $form->setData($data); 

     if ($form->isValid()) { 
      $data = $form->getData(); 
      // more code 
     } 
    } 

    return array('form' => $form); 
} 

現在,如果我提交表單,我得到驗證消息:

「的輸入似乎不是一個有效日期」

這是正確的,但我只希望如果需要現場就知道了。如果查看DateSelect元素的來源,我會看到一個getInputSpecification()方法,默認情況下需要設置爲false,並且還有一個getValidator()方法需要一個格式,其中空白日期不符合。

如果輸入不是必需的(顯然,以我真實的形式,我有更多的元素),如何繞過驗證?

回答

0

我通常使用工廠模式,你可以設置即

$inputFilter->add($factory->createInput(array(
      'name'  => 'availableDate', 
      'required' => true, 
      'filters' => array(
       array('name' => 'StripTags'), 
       array('name' => 'StringTrim'), 
      ), 
      'validators' => array(
       array(
        'name' => 'StringLength', 
        'options' => array(
         'encoding' => 'UTF-8', 
         'max'  => 20, 
        ), 
       ), 
      ), 
     ))); 

指所需的場場是否需要 - 你可以將其設置爲假