Code snippets for symfony 1.x

Navigation

Refine Tags

Snippets tagged "propel checkboxes"

Custom Validator for multiple checkboxes

While developing in symfony 1.0 I ran into the issue to validate how many checkboxes where actually checked. I created a custom validator class which was able to check for a minimum and a maximum value and throw corresponding error messages. Since I moved the project to symfony 1.2 I needed to update the validator, here is my solution (just place it somewhere in an autoloading directory like %project_root_dir%/lib and clean your cache):

class customValidatorPropelChoiceMany extends sfValidatorPropelChoiceMany
{
    protected function configure($options = array(), $messages = array())
    {
        parent::configure($options, $messages);
 
        $this->addOption('min', null);
        $this->addOption('max', null);
 
        $this->addMessage('min', 'Please select at least %min% fields.');
        $this->addMessage('max', 'Please do not select more than %max% fields.');
    }
 
    protected function doClean($value)
    {
        $value = parent::doClean($value);
 
        if ($this->getOption('multiple'))
        {
            if (count($value) < $this->getOption('min'))
            {
                throw new sfValidatorError($this, 'min', array('min' => $this->getOption('min')));
            }
            if (count($value) > $this->getOption('max'))
            {
                throw new sfValidatorError($this, 'max', array('max' => $this->getOption('max')));
            }
        }
 
        return $value;
    }
}
 

This code can easily be used to validate regular checkboxes (those which don't rely on a propel object), should be as easy as renaming the class and changing the parent to sfValidatorChoiceMany.

by Volker on 2009-03-04, tagged array  checkboxes  choice  propel  validator