Symfony 1.4 multi fields validator

In your form class (lib/form/doctrine/classForm.class.php)

  $this->validatorSchema->setPostValidator(
      new sfValidatorMultiFields(
        array('field1', 'field2', 'field3'),
        array('labels' => array('name1', 'name2', 'name3')),
        array('global_invalid' => 'Multi fields error')));

save this class in a lib folder, for exemple apps/frontend/lib/sfValidatorMultiFields.class.php

<?
class sfValidatorMultiFields extends sfValidatorSchema
{
 
  public function __construct(array $fields, $options = array(), $messages = array())
  {
    $this->addOption('fields', $fields);

    $this->addMessage('invalid', 'Error with this field');
    $this->addMessage('global_invalid', 'Multi fields error');

    parent::__construct(null, $options, $messages);
  }

  protected function doClean($values)
  {
    $valid = false;
    foreach ($this->getOption('fields') as $field) {
	//put here your validation code
        // ex: $values[$field] ....
    }
    //another example, at least one field in not empty
    if($values['field1'] != '' || $values['field2'] != '' || $values['field3'] != '')
    {
        $valid = true;
    }

    if ($valid)
    {
      $errorSchema = new sfValidatorErrorSchema($this);

        // The global error
        $errorSchema->addError(new sfValidatorError($this, 'global_invalid', array()));
      }

      // Fields error
      $error = new sfValidatorError($this, 'invalid', array()));

      // Add the error for each defined fields
      foreach ($this->getOption('fields') as $field)
      {
        $errorSchema->addError($error, $field);
      }

      throw $errorSchema;
    }

    return $values;
  }
}
?>

The keys points are :
– use $this->validatorSchema->setPostValidator() in your form class
– all fields are now available from the $values array ($values[‘field1′], $values[‘field2′] …)

Leave a Reply