用CakePHP修改一行
我使用CakePHP显示MySQL数据库表的前端GUI。我曾经自动生成屏幕,目前我有一个功能齐全的应用程序,每行有查看、编辑和删除按钮。我想为每行添加一个按钮,名为用CakePHP修改一行,php,mysql,cakephp,cakephp-2.4,Php,Mysql,Cakephp,Cakephp 2.4,我使用CakePHP显示MySQL数据库表的前端GUI。我曾经自动生成屏幕,目前我有一个功能齐全的应用程序,每行有查看、编辑和删除按钮。我想为每行添加一个按钮,名为Accept,它应该在SQL行上设置IsAccepted=1 我成功地为每行添加了一个Accept按钮,如下所示: echo $this->Html->link(__('Accept'), array('action' => 'accept', $product['Product']['ID'])) 但是Prod
Accept
,它应该在SQL行上设置IsAccepted=1
我成功地为每行添加了一个Accept
按钮,如下所示:
echo $this->Html->link(__('Accept'), array('action' => 'accept', $product['Product']['ID']))
但是ProductController.php
中的代码不起作用:
public function accept($id = null){
...
$this->Product->IsAccepted = 1; // does not work, silently fails
}
我做错了什么?如何使用每行按钮正确编辑一行?多亏了cornelb,我找到了答案!这是我用来修改行的最后一个代码,带有“每行”按钮
public function accept($id = null){
$this->Product->save(array('id' => $id, 'is_accepted' => 1));
}
- 按“每行”按钮时修改行(与POST/AJAX按钮类似)
- 显示“已接受!”的闪存消息显示保存是否成功
- 重定向回列表页面(似乎从未离开列表)
ProductController.php
中的代码(或您拥有的任何控制器类):
**试试这个**
只需从accept函数运行updateAll查询,如下所示:
public function accept($id = null){
if(!empty($id)){
$this->Product->updateAll(
array('Product.is_accepted' => 1),
array('Product.id' => $id)
);
}
}
希望这能帮助你
仅供参考:这不是任何当前或以前的CakePHP版本的工作方式。检查,并请始终提到您的确切CakePHP版本!另外,您调用的操作是“批准”,为什么函数名为“接受”?输入错误!很抱歉我当前的CakePHP版本是2.4.4。@ndm-按钮在上面显示的代码中每行都可见!我只是复制了用于查看和编辑的系统(它们都有相同的代码行,每个按钮1行)。。。我只是想不出控制器中的代码…很好的尝试,但出于某种原因,此代码执行“插入”。。。然后由于键“PRIMARY”的重复输入“1”而崩溃。!-“创建或更新由模型的id字段控制。如果设置了$model->id,则更新具有此主键的记录。否则将创建新记录。”。请尝试文档中描述的选项
public function accept($id = null) {
if ($this->Product->exists($id)) {
// save the row
// you absolutely need to fill the 'id' slot, even if its not your primary key!!
// this ensures that the row is EDITED, and not INSERTED!
if($this->Product->save(array('id' => $id, 'ID' => $id, 'IsApproved' => 1, 'ApprovedDate' => date('Y-m-d H:i:s', time())))){
// show a "flash" message
// (not Adobe Flash, just a message that shows on top of the list)
$this->Session->setFlash(__('The product has been accepted!'));
// this action does not have a view so no need to render
$this->autoRender = false;
// redirect to index view
return $this->redirect(array('action' => 'index'));
}
}
}
**Try this.....**
<?php
public function accept($id = null) {
$this->autoRender = false; // if action has not view.
if ($this->Product->exists($id)) {
$this->Product->id = $id;
if ($this->Product->save(array('is_accepted' => 1))) {
$this->Session->setFlash(__('The product has been accepted!'));
return $this->redirect(array('action' => 'index'));
}
}
}
?>
public function accept($id = null){
if(!empty($id)){
$this->Product->updateAll(
array('Product.is_accepted' => 1),
array('Product.id' => $id)
);
}
}