保存后在控制器中重置实体(或创建新的空实体) [英] Reset an entity (or create a new empty entity) in controller after saving

查看:120
本文介绍了保存后在控制器中重置实体(或创建新的空实体)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在保存后没有重定向(如果您保留在同一操作/网页上),保存后如何重置实体?

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)?

示例:I有一个页面列出所有用户。在同一页面上有添加新用户的表单。

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);
 }

我试图添加 $ user =''; c> $ user = $ this-> Users-> newEntity();

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).

推荐答案

我不知道如何将评论标记为我的问题的答案,所以我引用它:

I don't know how to mark a comment as the answer to my question, so I quote it:


您不只是在同一页上。保存是POST的结果,因此您需要之后按照PRG模式进行GET(重定向),为了避免其他问题出现,必须遵循PRG模式。然后你的问题解决了。所以总是重定向,在你的情况下只是到同一个网址。问题解决 - 按设计。 - mark

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

感谢@mark

这篇关于保存后在控制器中重置实体(或创建新的空实体)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆