在我要求用户确认他/她是否真的要删除这样的实例之前:
$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'));
}
答案 0 :(得分: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'));
}
}