CakePHP - 当尝试保存时验证失败时,编辑会丢失 URL 变量
用户从这里开始:
/admin/cuisines/edit/16
用户输入违反验证规则的内容,然后单击“提交”。用户被带到这里:
/admin/cuisines/edit/16
用户认为它是有效的,然后再次单击“提交” - 然后他们被带到这里:
/admin/cuisines/edit/
用户更正错误,单击“提交”,而不是进行编辑,而是将其保存为表中的新项目,因为没有ID。
我的代码:
function admin_edit($id = null) { // EDIT ***********
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid cuisine', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->Cuisine->save($this->data)) {
$this->Session->setFlash(__('The edits to this cuisine have been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The edits to this cuisine could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->Cuisine->read(null, $id);
}
}
对我做错了什么有什么想法吗?我以为我是按照教程做的,但是 - 我不得不猜测 Cake 足够聪明,不会让这种情况发生 - 即 - 我的假设是我做错了什么。
User starts here:
/admin/cuisines/edit/16
User types something in that is against validation rules and clicks Submit. User is taken here:
/admin/cuisines/edit/16
User thinks it IS valid and clicks submit again - they're then taken here:
/admin/cuisines/edit/
User corrects their mistake, clicks submit, and instead of an edit, it saves this as a new item in the table, since there's no id.
My code:
function admin_edit($id = null) { // EDIT ***********
if (!$id && empty($this->data)) {
$this->Session->setFlash(__('Invalid cuisine', true));
$this->redirect(array('action' => 'index'));
}
if (!empty($this->data)) {
if ($this->Cuisine->save($this->data)) {
$this->Session->setFlash(__('The edits to this cuisine have been saved', true));
$this->redirect(array('action' => 'index'));
} else {
$this->Session->setFlash(__('The edits to this cuisine could not be saved. Please, try again.', true));
}
}
if (empty($this->data)) {
$this->data = $this->Cuisine->read(null, $id);
}
}
Any thoughts on what I'm doing wrong? I thought I did it just like the tutorial, but - I would have to guess Cake is smart enough to not let this happen - ie - my assumption is I'm doing something wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了避免在提交编辑表单时保存新项目,请确保存在 id 的表单字段。
该字段将自动隐藏,因为它是模型的主键。
还要检查 HTML 中的表单操作属性。有时我必须手动设置它以避免错误。
To avoid the saving of new items when the edit form is submitted, make sure that a form field for the id is present.
This field will be hidden automatically because it is the models primary key.
Also check the form action attribute in the HTML. I sometimes have to set it manually to avoid it being wrong.