Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "validator box"

How to validate that at least one checkbox has been checked

I spent some time trying to figure out how to make sure that one checkbox was checked before saving a form in symfony 1.2.

I read about Global Validators (http://www.symfony-project.org/forms/1_2/en/02-Form-Validation#chapter_02_global_validators) but I couldn't find anything to fit my needs. Finally, after looking at this snipped: http://www.symfony-project.org/cookbook/1_2/en/conditional-validator , I created the validation I needed, here is the snipped to help someone in the same situation:

class SampleForm extends BaseSampleForm
{
  public function configure()
  {
 
  // add a post validator
    $this->validatorSchema->setPostValidator(
      new sfValidatorCallback(array('callback' => array($this, 'checkAtLeastOne')))
    );
 
 
    unset(
      $this['created_at'], $this['updated_at']
 
    );
  }
 
  public function checkAtLeastOne($validator, $values)
  {
    if (!$values['sunday'] && !$values['monday'] && !$values['tuesday'] && !$values['wednesday'] && !$values['thursday'] && !$values['friday'] && !$values['saturday'])
    {
      // no checkbox was checked, throw an error
      throw new sfValidatorError($validator, 'Check at least one day of the week');
    }
 
    // at least one checkbox is checked, return the clean values
    return $values;
  }
 
 
}
 
by carlos m on 2009-06-26, tagged box  check  checkbox  checked  form  global  validator 
(2 comments)