Search code examples
symfony1sfdoctrineguard

Symfony admin generator : add user id before saving


I'm creating my own blog engine to learn Symfony, and I have a question :

In the generated administration pages for a blog post, I have a drop-down list of authors, to indicate the author_id.

I'd like to hide that drop-down list, and set the author_id to the id of the current logged-in user when the post is created (but not when it is edited)

How can I accomplish that ?

Edit I've tried those :

$request->setParameter(sprintf("%s[%s]", $this->form->getName(), "author_id"), $this->getUser()->getAttribute("user_id"));
$request->setParameter("content[author_id]", $this->getUser()->getAttribute("user_id"));
$request->setParameter("author_id", $this->getUser()->getAttribute("user_id"));
$request->setParameter("author_id", 2);
$request->setParameter("content[author_id]", 2);
$request->setParameter("author_id", "2");
$request->setParameter("content[author_id]", "2");

In processForm() and executeCreate()

Resolved !

The final code is :

  public function executeCreate(sfWebRequest $request)
  {
    $form = $this->configuration->getForm();
    $params = $request->getParameter($form->getName());
    $params["author_id"] = $this->getUser()->getGuardUser()->getId();;
    $request->setParameter($form->getName(), $params);

    parent::executeCreate($request);

  }

Solution

  • Override the executeCreate function in the actions file. When binding post data to the form, merge the current user's id into it.

    2nd update

    I did some experimenting, and this works:

    class fooActions extends autoFooActions
    {
      public function executeCreate(sfWebRequest $request)
      {
        $form = $this->configuration->getForm();
        $params = $request->getParameter($form->getName());
        $params["author_id"] = 123;
        $request->setParameter($form->getName(), $params);
    
        parent::executeCreate($request);
      }
    }