Cakephp 3.x重定向不使用同一函数中的另一个方法在同一个控制器中工作

时间:2016-10-06 10:09:33

标签: cakephp cakephp-3.0 cakephp-3.x

我正在使用 cakephp 3.x ,我在我的控制器中有一个编辑功能,我在其中检查id是否在查询字符串中,以及是否存在于数据库记录中。下面是我的代码,它的工作非常好。

UsersController.php

public function edit($id = null)    
{

    // first checking whether id sent or not .. 
    if(empty($this->request->params['pass']))
    {
        $this->Flash->error('Invalid Action');
        return $this->redirect(['action' => 'index']);
    }        


    // Now checking whether this user id exists or 

    $check_user = $this->Users
                    ->find()
                    ->where(['user_id' => $id])
                    ->toArray();
    if(!$check_user)
    {
         $this->Flash->error('Invalid Id, User not found');
        return $this->redirect(['action' => 'index']);
    }

    $user = $this->Users->get($id); 

    // And so on 
 }

问题是,我在许多其他函数中使用相同的代码来检查相同的事情,所以我想在同一个控制器中创建一个通用函数并在下面的多个函数中使用它。

UsersController.php (已更新)

public function checkId($id)
{
    // first checking whether id sent or not .. 
    if(empty($this->request->params['pass']))
    {
        $this->Flash->error('Invalid Action');
        return $this->redirect(['action' => 'index']);
    }        


    // Now checking whether this user id exists or 

    $check_user = $this->Users
                    ->find()
                    ->where(['user_id' => $id])
                    ->toArray();
    if(!$check_user)
    {
         $this->Flash->error('Invalid Id, User not found');
        return $this->redirect(['action' => 'index']);
    }
}

public function edit($id = null)    
{
    $this->checkId($id);
}

现在,如果我在浏览器中执行网址 http://localhost/5p_group/users/edit/ ,我会收到此错误,说明记录未在表格中找到"用户"主键为[NULL]

有人可以指导我如何使用我在上面创建的常用功能来完全填充这两个条件(检查网址中的ID或不是有效ID),使用我在上面创建的常用功能..如果我放的话,它工作得非常好该代码位于我的 edit()函数中。

任何帮助或建议都将受到高度赞赏。

谢谢

1 个答案:

答案 0 :(得分:0)

在您的代码中,您忘记添加函数参数$ id,您已在查询中使用它

public function checkId()

更改为

public function checkId($id)

[更新]

这也是函数返回问题

if(empty($id))
{
    $this->Flash->error('Invalid Action');
    return $this->redirect(['action' => 'index']);
}

更改为>>

if(empty($id))
{
    $this->Flash->error('Invalid Action');
    $this->response = $this->redirect(['action' => 'index']) ;
    $this->response->send () ;
    die () ;
}
相关问题