Change required parameter of fields Fieldset Fields

I have a moneyFieldset with two fields, amount and currency.

class MoneyFieldset ... { public function __construct($name = null, $options = array()) { parent::__construct($name, $options); $this->setHydrator(...); $this->add(array( 'name' => 'currency', 'type' => 'select', 'options' => array( 'value_options' => \Core\Service\Money::getAvailableCurrencies(true), ), 'attributes' => array( 'value' => \Core\Service\Money::DEFAULT_CURRENCY, ), )); $this->add(array( 'name' => 'amount', 'type' => 'text', )); } } public function getInputFilterSpecification() { $default = [ 'amount' => [ 'required' => false, 'allow_empty' => true, 'filters' => [ ['name' => AmountFilter::class] ], 'validators' => [ ] ], 'currency' => [ 'required' => false, 'allow_empty' => true, 'filters' => [ ['name' => StringToUpper::class] ], 'validators' => [ ] ] ]; return \Zend\Stdlib\ArrayUtils::merge($default, $this->filterSpec, true); } 

I use moneyFieldset in my other fields, for example:

  // Price Field $this->add(array( 'name' => 'price', 'type' => 'form.fieldset.moneyFieldset', 'attributes' => array( 'required' => true, 'invalidText' => 'Please type an amount' ), 'options' => array( ... ), )); 

When I set the filter as follows:

  function getInputFilterSpecification() { 'price' => [ 'required' => true, 'allow_empty' => false, ], } 

This does not work because the price has 2 fields, so how can I say that the price [amount] and price [curreny] are not required?

+5
source share
2 answers

You can provide input specifications for a nested set of fields (in the context of a form) using the following array structure.

 public function getInputFilterSpecification() { return [ // ... 'price' => [ 'type' => 'Zend\InputFilter\InputFilter', 'amount' => [ 'required' => true, ], 'currency' => [ 'required' => true, ] ], //... ]; } 

If you dynamically change the values โ€‹โ€‹of an input filter, it might be worth considering creating a validator using the factory class and then binding it to the form using the object's API, not arrays.

+4
source

As I said in a comment by @AlexP, a field or group of fields declared to be required, such as:

 function getInputFilterSpecification() { 'price' => [ 'required' => true, 'allow_empty' => false, ], } 

Doesn't mean that it will print html like this:

 <input type="text" required="required"/> 

Just check when you do $form->isValid() if your fields are empty and required or other checks. To do this, you just need to set the attributes that you want to use for these fields. As you already did. Attributes can add, like the class attribute, html code for input.

PS: AlexP's answer is the best answer. I just give more information about this.

+3
source

Source: https://habr.com/ru/post/1239194/


All Articles