问题
I have a action class for saving some data to a database.In action class iam getting a id through url.I have to save the id in table.
I am getting the id by $request->getParameter('id')
I used this code for saving
$this->form->bind($request->getParameter('question_answers'));
if ($this->form->isValid())
{
$this->form->save();
$this->redirect('@homepage');
}
in model class i used a override save method to save extra field
public function save(Doctrine_Connection $conn = null) { if ($this->isNew()) {
$now=date('Y-m-d H:i:s', time());
$this->setPostedAt($now);
} return parent::save($conn); so i want to get the id value here . So how can i pass id value from action class to model class
is any-other way to save the id in action class itself Thanks in advance
回答1:
Just use
$this->form->getObject()->setQuestionId($request->getParameter('id')); $this->form->save();
QuestionId=field name
$request->getParameter('id')= is the default value
回答2:
Most probably not the best solution but you can save that id value in a session variable and use it later anywhere you need. something like:
$this->getUser()->setAttribute('id', $request->getParameter('id')); // in action class
and
sfContext::getInstance()->getUser()->getAttribute('id'); // in model class
回答3:
If your model has a field for this ID already (eg in your example posted_id), then you can do one of 2 things:
1: Pass the ID to your form when you create it, as an option:
$this->form = new MyForm(array(), array("posted_id" => $id));
and then you can override your form's doSave() method to set the field:
// ...
$this->getObject()->posted_id = $this->getOption("posted_id");
// ...
or similar
2: Add a widget to your form in the configure() method with a corresponding validator, and pass in the ID when you get the values from the request:
$values = $request->getParameter('question_answers');
$values["posted_id"] = $request->getParameter("id");
$this->form->bind($values);
If you're rendering your form manually, just don't render this new field in your view template.
Either way, saving the model as a result of the form saving it will include this new field I believe. The second one is from memory, but it should technically work... :-)
回答4:
Best practice I'm using consists of 2 steps:
- Pass additional data to forms' options (2nd constructor's parameter or just
$form->setOption('name', 'value')
); override protected method
doUpdateObject
in way like this:protected function doUpdateObject($values) { $this->getObject()->setFoo($this->getOption('foo')); parent::doUpdateObject($values); }
Enjoy!
回答5:
You could use (sfUser)->setFlash and (sfUser)->getFlash instead of setAttribute, it's more secure...
来源:https://stackoverflow.com/questions/2461585/passing-values-from-action-class-to-model-class-in-symfony