Reputation: 1133
Before I would just ask user to confirm if he/she really wants to delete any instance like this:
$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?'));
Right now user hasMany events, and I would like to check if he/she really does. That's no problem, so in the controller I would just try to get the first event his that user's id. But then, if there are any events, I would like to notify the users, that the deletion is not possible because there are related events.
I can go around and come up with some custom javascript solution, but there has to be a cake way to do it, it is just I cant find any.
Any suggestions?
Here is the controller action as of right now:
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'));
}
Upvotes: 1
Views: 874
Reputation: 594
Given that you have properly set up the model relationships like this:
//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'));
}
}
Upvotes: 1