【问题标题】:Conditional user confirmation on delete cakePHP删除 cakePHP 的条件用户确认
【发布时间】:2014-05-22 14:04:42
【问题描述】:

在我只要求用户确认他/她是否真的想删除任何这样的实例之前:

$this->Html->link($this->Html->image('delete.png', array(
'alt'=>'delete', 'title'=>__('Delete'))),
 array(
'controller' => 'users', 'action' => 'delete', $user['User']['id']),
  array(
'escape'=>false, 'confirm'=>'Are you sure, you want to delete this user?'));

现在用户有很多事件,我想检查他/她是否真的有。没问题,所以在控制器中我会尝试获取第一个事件他的那个用户的 id。但是,如果有任何事件,我想通知用户,因为有相关事件,所以无法删除。

我可以四处寻找一些自定义的 javascript 解决方案,但必须有一个蛋糕的方法来做到这一点,只是我找不到。

有什么建议吗?

这是目前的控制器操作:

public function delete($id = null,$user_id = null) {
    if (!$id) {
        $this->Session->setFlash(__('Incorrect user id'));
        $this->redirect(array('action'=>'index'));
    }
    if ($this->User->delete($id)) {
        $this->Session->setFlash(__('User has been deleted'), 'positive_notification');
        $this->redirect(array('controller'=>'full_calendar', 'action'=>'view_for', $user_id ));
    }
    $this->Session->setFlash(__('The user could not be deleted. Please try again.'), 'negative_notification');
    $this->redirect(array('action' => 'index'));
}

【问题讨论】:

  • 刚刚用控制器操作更新了问题。
  • 是的,这将通过 GET 工作,这使得它对 CSRF 攻击敞开了大门。在等待答案的同时,我建议调查如何通过邮寄方式使其工作,以及如何在您的视图中使用 postLink。您提出的问题仍然适用,因为您要问的是有效地如何实现 beforeDelete 方法。

标签: cakephp cakephp-2.3


【解决方案1】:

假设您已正确设置模型关系,如下所示:

   //User.php

   public $hasMany = array(
    'Event' => array(
        'className' => 'Event',
        'foreignKey' => 'user_id'
    ),

  //Event.php
   public $belongsTo = array(
    'User' => array(
        'className' => 'User',
        'foreignKey' => 'user_id'
    ),
);


 public function delete($id = null) {
    if (!$id) {
      $this->Session->setFlash(__('Incorrect user id'));
      $this->redirect(array('action'=>'index'));
    }
    //check if User has Events
    $user=$this->User->findById($id); //you can debug first the $user so you can know the values inside the array. Given that it has many Events, events associated to the User is in the $user
    if(count($user["Event"])==0){ //if user has no events
       if ($this->User->delete($id)) { //delete user
          $this->Session->setFlash(__('User has been deleted'), 'positive_notification');
          $this->redirect(array('controller'=>'full_calendar', 'action'=>'view_for', $user_id ));
       }
       else{
            $this->Session->setFlash(__('The user could not be deleted. Please try again.'),             'negative_notification');
         $this->redirect(array('action' => 'index'));
       }
    }
    else{
         $this->Session->setFlash(__('The user could not be deleted. Some events are associated to this User.'), 'negative_notification');
         $this->redirect(array('action' => 'index'));
    }


}

【讨论】:

    猜你喜欢
    • 2014-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多