Sunday 31 January 2010

Auto setting a user's group(s) using sfDoctrineGuardPlugin

I tried a number of different ways to achieve adding a user to a group automatically today before stumbling across the 'correct' way as per a forum reply from Fabien himself today.

I was trying all sorts of different methods, in the form, in the action, whereever... and finally it was pretty easy.

So let's assume you have RegisterForm which extends the sfGuardUserForm. The proper way to do it is in the doSave method of that form.

So your code might look something like...


class RegisterForm extends sfGuardUserForm
{
    //...
    protected function doSave($con = null)
    {
        $isNew = $this->isNew(); // set this here, because it will change before you want to test for it...
         // ... any other pre-processing that needs to be done...

        parent::doSave($con);

        if($isNew)
        {
            $group = Doctrine::getTable('sfGuardGroup')->findOneByName('customer');
            $this->getObject()->link('groups',$group->getId());
        }
    }
    //...
}

Quite easy when you know how and I guess this would be the way to auto-select other, required relationships too...

No comments:

Post a Comment

Please leave your feedback and comments. I love to discuss this stuff!