Code snippets for symfony 1.x

Navigation

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 

Comments on this snippet

gravatar icon
#1 Jamie Learmonth on 2009-06-28 at 02:18

If you sfWidfgetFormSelectCheckbox() instead of sfWidgetFormSelectInput() you can group those days. See http://www.symfony-project.org/forms/1_2/en/A-Widgets#chapter_a_sub_choices_grouping

gravatar icon
#2 carlos m on 2009-06-30 at 04:39

I don't think I'm using sfWidgetFormInput() all those fields are checkboxes generated from boolean columns. Even if I had grouped them my problem was the validation.