Cakephp 3.x Ajax删除数据会出现此错误:未知方法“isNew”

时间:2015-06-09 17:11:43

标签: php ajax cakephp cakephp-3.0

我尝试在CakePhp 3.0.6中使用Ajax删除记录。

以下是我的View(start.ctp)中的jquery

<script>
$('.delavailable').click(function(){
    var dataString = 'ID=' + $(this).attr('id');
    $.ajax({
        type: 'POST',
        url: '/ID/admins/delavailable.json',
        data: dataString,
        beforeSend: function(xhr) {
            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
        }
    });
});

Controller(AdminsController.php)

    public function delavailable()
{

    $this->loadModel('TeamFree');

    if($this->request->is('ajax')) {
        $this->TeamFree->delavailable($this->request->data['ID']);
    }
}

模型/表(TeamFreeTable.php)

    public function delavailable($id){

         $query = $this->find('all')
        ->select(['TeamFree.ID'])
        ->where(['TeamFree.ID ='=>$id]);

        $this->delete($query);
}

返回

{
"message": "Unknown method \u0022isNew\u0022",
"url": "\/ID\/admins\/delavailable.json",
"code": 500

}

我在哪里失败?

2 个答案:

答案 0 :(得分:2)

您正在将查询对象传递给Table::delete(),这不是它的工作方式,该方法需要一个实体,您必须事先获取该实体。

简化示例

$this->delete($this->get($id));

另见

答案 1 :(得分:0)

感谢Cookbook和一些试验和错误,这就是我设法通过Ajax删除行的方法。

    public function delavailable()
{

    $this->loadModel('TeamFree');

    $teamfree = $this->TeamFree->newEntity(); //create a temporary entity

    if($this->request->is('ajax')) {
        $teamfree = $this->TeamFree->patchEntity($teamfree,$this->request->data); // put the request data into the temp entity
        $this->TeamFree->delete($this->TeamFree->get($teamfree->ID)); //use get() to place the entity property into the delete function and let the delete function refer to the entity
    }
}