0

我正在使用 CakePHP 显示 MySQL 数据库表的前端 GUI。我已经使用bake来自动生成屏幕,我目前有一个功能齐全的应用程序,每行都有查看、编辑和删除按钮。我想为每行添加一个名为 的按钮,该按钮Accept应设置IsAccepted = 1在 SQL 行上。

我设法为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
 }

我究竟做错了什么?如何使用每行按钮正确编辑一行?

4

5 回答 5

1
public function accept($id = null){
     $this->Product->save(array('id' => $id, 'is_accepted' => 1));
}
于 2014-01-13T13:20:50.027 回答
0
// assuming cake 2.1+
public function accept($id = null){
    if($this->Product->exists($id)) {
        $this->Product->saveField('is_accepted', 1);
        // success.. 
    }

    // else throw not found exception... 
}
于 2014-01-13T13:31:54.797 回答
0

感谢cornelb,我找到了答案!这是我用来修改行的最终代码,带有每行按钮。

  • 按下每行按钮时修改行(就像 POST/AJAX 按钮一样工作)
  • 一条显示“已接受!”的消息。显示是否保存成功
  • 重定向回列表页面(似乎永远不会离开列表)

这是进入的代码ProductController.php(或您拥有的任何控制器类):

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'));
        }
    }
}
于 2014-01-13T13:36:42.167 回答
0
    **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'));
        }
    }
}
?>
于 2014-01-14T06:07:31.470 回答
0

只需从接受函数运行 updateAll 查询,如下所示:

public function accept($id = null){

  if(!empty($id)){
   $this->Product->updateAll(
    array('Product.is_accepted' => 1),
    array('Product.id' => $id)
   );
  }

}

希望对你有帮助...

供参考:http ://book.cakephp.org/2.0/en/models/saving-your-data.html

于 2014-01-14T06:46:56.203 回答