2015-10-26 97 views
1

我只是想在表單中創建一個Date元素,但日期格式總是「mm/dd/yyyy」,不管我怎麼改變它。我試圖將其設置是這樣的:無法爲Zend Framework 2日期表單元素設置日期格式?

$this->add(array(
     'name' => 'ct-start_date', 
     'options' => array(
        'label' => 'Start Date', 
        'format'=>'Y-m-d' 
        ), 
     'attributes' => array(
      'class' => 'ct-date', 
     ), 
     'type' => 'Zend\Form\Element\Date', 
    )); 

,並顯示如下:

echo $this->formRow($form->get('ct-start_date')); 

但它仍然出來爲 「MM/DD/YYYY」 即使當我做:

print_r($form->get('ct-start_date')->getFormat()); 

作爲「Ymd」出現!所以我補充說:

$this->get('ct-start_date')->setOptions(array('format'=>'Y-m-d')); 

沒有變化。然後我試過這個:

$date = new Element\Date('ct-start_date'); 
    $date 
     ->setLabel('Start Date') 
     ->setAttributes(array(
      'class' => 'ct-date', 
     )) 
     ->setOptions(array(
      'format' => 'Y-m-d' 
     )); 
    $this->add($date); 

同樣的事情!這在Chrome中。在Firefox中它只是一個空文本輸入。也許我應該回顧一下jQuery。

回答

0

Date元素中的format選項不會影響元素中日期的輸入或輸出格式。

元素的getInputSpecification()方法使用它來確定驗證器使用的日期格式。

實施例:

$this->add(array(
    'name' => 'ct-start_date', 
    'options' => array(
       'label' => 'Start Date', 
       'format'=>'Y-m-d' 
       ), 
    'attributes' => array(
     'class' => 'ct-date', 
    ), 
    'type' => 'Zend\Form\Element\Date', 
)); 

//... 

public function getInputFilter() 
{ 
    $filter = new InputFilter() 

    // add default filters and validators for the date element 
    // the date validator will automatically be set up to accept dates 
    // formatted according to your elemen's "format" option 
    $filter->add($this->get('ct-start-date')->getInputSpecification()); 

    ../ 
    return $filter; 
} 

如果打算從服務器側的日期值來填充表單元素,它需要以適當的格式(例如$element->setValue(date('Y-m-d', $date));

在客戶端那麼他們需要以適當的格式輸入它,否則驗證器將返回一個錯誤,或者確保您使用的任何客戶端日期輸入將其放入Y-m-d格式中。