What is the correct way to add validation on the form level in ZF2?

123 Views Asked by At

There is a complex form with a lot of nested fieldsets. Some fields need to be validated depending on field(-s) in another fieldset. So I cannot define all the validation rules directly in the getInputFilterSpecification() of the Fieldset, since there I cannot access other fieldsets (only the sub-fieldsets). The only way to do this is to extend the Form validation. Right? If so, how to do this?

MyForm extends Form
{
    public function isValid()
    {
        $isFormValid = parent::isValid();
        $isFieldXyzValid = // my additional validation logic
        if(! $isFieldXyzValid) {
            $fieldXyz->setMessages(...);
        }
        return $isFormValid && $isFieldXyzValid;
    }
}

Like this? Or is a cleaner way to solve this problem?

1

There are 1 best solutions below

2
On

I've already developed something similar in my previous project.

For doing this i used a service which take my form and set dynamic fieldset, and obviously custom validation rules.

In your controller, get your form (via the dependancy injection formManager (polyfilled or not).

$form = $this->formManager->get('{your form}');

Call your service and give it your form.

And in your service you can do anything you want like :

  • get your stuff (from DB or others) to determine wich fields are mandatory
  • Foreach on your form
  • Add or remove fieldset
  • Add or remove validationGroup fields
  • Add or remove filters
  • Add or remove validators

I performed those via (sample) in a foreach where $stuff is an element of doctrine collection

$nameFieldset = 'my_fieldset-'.$stuff->getId();
            $globalValidator = new GlobalValidator();
            $globalValidator->setGlobalValue($gloablValue);

            $uoValidator = new UcValidator();
            $uoValidator->setOptions(array(
                'idToValidate' => $stuff->getId(),
                'translator' => $this->translator
            ));

            $globalValidator->setOptions(array(
                'idToValidate' => $stuff->getId(),
                'translator' => $this->translator
            ));

            $name = 'qty-'.$stuff->getId();

            $form = $this->setFilters($form, $name, $nameFieldset);
            $globalValidator->setData($data);
            $form = $this->setValidators($form, $name, $globalValidator, $uoValidator, $nameFieldset);

Where setFilters and setValidators are custom methods wich add filters and validator to my fields (also custom)

/**
 * @param myForm $form
 * @param $name
 * @param string $nameFieldset
 * @return myForm
 */
public function setFilters($form, $name, $nameFieldset)
{
    $form->getInputFilter()->get('items')->get($nameFieldset)
        ->get($name)
        ->getFilterChain()
        ->getFilters()
        ->insert(new StripTags())
        ->insert(new StringTrim());

    return $form;
}


/**
 * @param myForm $form
 * @param $name
 * @param $globalValidator
 * @param $uoValidator
 * @param $nameFieldset
 * @return myForm
 */
public function setValidators($form, $name, $globalValidator, $uoValidator, $nameFieldset)
{
    $optionsSpace = [
        'translator' => $this->translator,
        'type' => NotEmpty::SPACE
    ];
    $optionsString = [
        'translator' => $this->translator,
        'type' => NotEmpty::STRING
    ];
    $optionsDigits = [
        'translator' => $this->translator,
    ];
    $form->getInputFilter()->get('items')
        ->get($nameFieldset)
        ->get($name)
        ->setRequired(true)
        ->getValidatorChain()
        ->attach($uoValidator, true, 1)
        ->attach($globalValidator, true, 1)
        // We authorize zéro but not space nor strings
        ->attach(new NotEmpty($optionsSpace), true, 2)
        ->attach(new NotEmpty($optionsString), true, 2)
        ->attach(new Digits($optionsDigits), true, 2);
    return $form;
}