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()->get开发者_运维技巧Attribute("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);
}
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);
}
}
change the widget in the form with the sfWidgetFormInputHidden and set the value with sfUser attribute (that defined when a user logged in)
override the executeCreate() and set the author_id widget (thanks to maerlyn :D )
public function executeCreate(sfWebRequest $request){
parent::executeCreate($request);
$this->form->setWidget('author_id', new sfWidgetFormInputHidden(array(),array('value'=>$this->getUser()->getAttribute('author_id'))) );
}
In Objects , the solution is: (new and $this)
class fooActions extends autoFooActions
{
public function executeCreate(sfWebRequest $request)
{
$this->form = new XxxxxForm();
$params = $request->getParameter($this->form->getName());
$params["author_id"] = 123;
$request->setParameter($this->form->getName(), $params);
parent::executeCreate($request);
}
}
精彩评论