Pass userId to from set default to current user

215 Views Asked by At

A quick question. I'm using symfony1.4 with Doctrine ORM and sfGuardDoctrinePlugin. I have a symfony form named 'task'. I want the userId field (FK to Id fied if user table) to be set by default to the current logged user. How can I achieve this?

//apps/myapp/modules/task/actions

class taskActions extends sfActions
{
  public function executeNew(sfWebRequest $request)
  {
    $this->form = new taskForm();
  }

  public function executeCreate(sfWebRequest $request)
   {
    $this->forward404Unless($request->isMethod(sfRequest::POST));

    $this->form = new taskForm();

    $this->processForm($request, $this->form);

    $this->setTemplate('new');
  }
}
1

There are 1 best solutions below

2
On BEST ANSWER

Kind of tricky to answer without seeing how you are setting up the form through the actions, or through the $form->configure(), but you can access the current user id using this:

$currentUserId = sfContext::getInstance()->getUser()->getGuardUser()->getId();

-- Update --

Based on your update it appears that taskForm is not based off of a model object, otherwise you would be passing an object through the constructor, so it must be a custom form. There are a couple of ways to skin this cat, you can either pass the user object through the constructor or you can set the value through a public accessor, like this:

class taskForm
{
    protected $user;

    public function setUser($user)
    {
        $this->user = $user;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function configure()
    {
        // This should output the current user id which demonstrates that you now
        // have access to user attributes in your form class
        var_dump($this->getUser()->getGuardUser()->getId()); 
    }
}

And to set it:

public function executeNew(sfWebRequest $request)
{
    $this->form = new taskForm();

    $this->form->setUser($this->getUser());
}

Another way you may be able to do it is to pass the user object straight through the constructor, then you can reference it using $this->getObject()->getUser() while in form, although I don't recommend this as it forces the taskForm within a user context.