2017-06-15 7 views
1

私はフォームの要素のリストを持っていますが、そのうちの1つは単純なyes/noオプションを持つ選択ボックスです。フィールドが「いいえ」のときは、次の入力フィールドを必要としたい。現時点でZF2別の要素に基づいて必要なフォーム要素のみを作成しますか?

私の入力フィルタのようになります。私はadditionalフィールドの'required' => false,validators実行のどれを持っているので、私は発見しています何

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', 
        ], 
       ], 
      ], 
     ], 
    ], 
]; 

です。

conditionが 'いいえ'(値 '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', 
        ], 
       ], 
      ], 
     ], 
    ], 
]; 
関連する問題