Issue
On CakePHPs blog tutorial there will be a post saved by following action:
public function add()
{
if ($this->request->is('post'))
{
$this->Post->create();
if ($this->Post->save($this->request->data))
{
$this->Session->setFlash(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to add your post.'));
}
}
I not really understand the purpose of $this->Post->create();
described in Cookbook:
[...]it resets the model state for saving new information. It does not actually create a record in the database but clears Model::$id [...]
(Found at Cookbook 2.x)
What will happen, if Model::$id will not be cleared by create();
?
Solution
I understand your question to (now) mean:
Can I leave out the create call in this code example:
Yes, yes you can
Model::create resets the model to a consistent state, deleting the data property and resetting the id to null.
This method only does something/anything if the model has been modified; if the model state hasn't been modified, or it's the first called method of an action it won't do anything - but it's a good habit to always call create
whenever the existing model state is not relevant to the next model method call, and can prevent unexpected application bugs.
Answered By - AD7six Answer Checked By - Katrina (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.