问题
How do you reset an entity after saving it if there is not a redirect after saving (if you stay on the same action/page)?
Example: I have a page listing all users. On the same page there is the form to add a new user.
public function index() {
$this->set('listallusers', $this->Users->find('all'));
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
$user = $this->Users->patchEntity($user, $this->request->data );
if ( $this->Users->save($user) ) {
$this->Flash->succeed('User saved.');
// line 8
} else {
$this->Flash->error('There is an error.');
}
}
$this->set('user', $user);
}
I tried to add $user = '';
after the flash message in line 08, as well as $user = $this->Users->newEntity();
But the form on the page is still containing/showing the values of the last saved user (I want to have an empty form when the saving was successfull).
回答1:
I don't know how to mark a comment as the answer to my question, so I quote it:
You don't just stay on the same page. A save is the result from a POST, thus you need to make a GET (redirect) afterwards to follow the PRG pattern, which you must follow for several reasons to avoid other issues coming up. Then your issue resolves itself. So ALWAYS redirect, in your case just to the same URL again. Problem solved - by design. – mark
Thank you @mark
来源:https://stackoverflow.com/questions/31006015/reset-an-entity-or-create-a-new-empty-entity-in-controller-after-saving