Code snippets for symfony 1.x

Navigation

Snippets by user Volker

Check if a user is in one or more groups

Extend the myUser.class.php in any /lib folder with the following function:

public function isInGroups(array $groups, $strict = false)
{
    if ($strict)
    {
        return (array_intersect($groups, $this->getGroupNames()) == $groups);
    }
    else
    {
        foreach ($groups as $g)
        {
            if (in_array($g, $this->getGroupNames())) return true;
        }
    }
    return false;
}
 

Now you can check the groups of the user as following:

if ($sf_user->isInGroups(array('admin', 'editor')))
{
    // do stuff here...
}
 

You can also check if the user is in all the groups specified. Just set the second parameter to true:

if ($sf_user->isInGroups(array('admin', 'editor'), true))
{
    // this is executed only if the user is in the groups admin AND editor
    // please note: he might still be a member of other groups
}
 
by Volker on 2009-09-18, tagged check  group  groups  user 
(2 comments)

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