doukanhua0752 2014-01-20 23:40
浏览 15
已采纳

CakePHP:删除前检查用户的group_id

I'm trying to protect administrators from accidentally deleting each other in CakePHP 2.4 by checking the group_id. I tried using the following delete method, but it deletes the user anyway and doesn't redirect. How do I return the group_id of the user and then redirect and display an appropriate flash saying "Administrators cannot be deleted"?

public function delete($id = null) {
    if (!$this->request->is('post')) {
        throw new MethodNotAllowedException();
    }
    $this->User->id = $id;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }
    if ($user['User']['group_id'] == 1) { //Check user group
        $this->Session->setFlash(__('Administrators can not be deleted'), 'flash/error');
        $this->redirect(array('action' => 'index'));
        }

    if (!$this->User->delete()) {
        $this->Session->setFlash(__('User could not be deleted'), 'flash/error');
        $this->redirect(array('action' => 'index'));
        }

    if ($this->User->delete()) {
        $this->Session->setFlash(__('User deleted'), 'flash/success');
        $this->redirect(array('action' => 'index'));

}}

  • 写回答

1条回答 默认 最新

  • doujuanqi2909 2014-01-21 00:09
    关注
    1. You have a typo in your code -- change your = to == ; then your if statement shouldn't be evaluating as true all the time

      if ($user['User']['group_id'] == '1') 
      
    2. Session is either a component (part of the Controller layer) or a helper (part of the View layer) -- it is not intended to be used in the Model, nor should it be used in the model, generally. And redirect() is a controller method only. Just have beforeDelete return false, and then in your controller have a check to see if the delete failed (i.e. it returned false), and if so, show your error flash message, and redirect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示