2017-06-15 102 views
1

所以我有我的表單中的元素列表,其中之一是一個簡單的是/否選項的選擇框。當該字段爲「否」時,我想使下一個輸入字段成爲必需。ZF2只根據另一個元素創建一個表單元素?

此刻我的輸入濾波器的樣子:

return [ 
    [ 
     'name' => 'condition', 
     'required' => true, 
    ], 
    [ 
     'name' => 'additional', 
     'required' => false, 
     'validators' => [ 
      [ 
       'name' => 'callback', 
       'options' => [ 
        'callback' => function($value, $context) { 
         //If condition is "NO", mark required 
         if($context['condition'] === '0' && strlen($value) === 0) { 
          return false; 
         } 
         return true; 
        }, 
        'messages' => [ 
         'callbackValue' => 'Additional details are required', 
        ], 
       ], 
      ], 
      [ 
       'name' => 'string_length', 
       'options' => [ 
        'max' => 255, 
        'messages' => [ 
         'stringLengthTooLong' => 'The input must be less than or equal to %max% characters long', 
        ], 
       ], 
      ], 
     ], 
    ], 
]; 

什麼我發現是因爲我有'required' => false,additional場,沒有validators運行。

僅當condition爲'no'(值'0')時,我該如何製作additional

回答

1

可以從getInputFilterSpecification函數中檢索元素。因此,有可能基於其他因素的相同形式或字段集的值的元素標記爲required與否:

'required' => $this->get('condition')->getValue() === '0', 

有了這個,我也可以擺脫大規模callback驗證過。

return [ 
    [ 
     'name' => 'condition', 
     'required' => true, 
    ], 
    [ 
     'name' => 'additional', 
     'required' => $this->get('condition')->getValue() === '0', 
     'validators' => [ 
      [ 
       'name' => 'string_length', 
       'options' => [ 
        'max' => 255, 
        'messages' => [ 
         'stringLengthTooLong' => 'The input must be less than or equal to %max% characters long', 
        ], 
       ], 
      ], 
     ], 
    ], 
]; 
相關問題