CakePHP deleteButton when SoftDelete Behavior in Effect

Here is a piece of code placed as a helper function. Useful to create a delete button/link while having SoftDeleteBehavior enabled for a Model. For example, placed in data management page (view page such as admin_index.ctp or index.ctp) of your application.

[php]echo $this->Utility->deleteButton($course, ‘Course’);[/php]

Where $course is a data row having Course as a first index set. For exaample:

[php]
array(
‘Course’=> array(
‘id’=>1,
‘name’=>’Course Name’,
‘other_field’=>’field_value’,
…..
…..
)
)
[/php]

Here is the helper function.

[php]
/**
* delete_button method
*
* Generated delete links based on the SoftDelete behaviour actions.
*
* @throws NotFoundException
* @param array $data – A db row containing a recordset
* @return string HTML
*/
function deleteButton($data, $modelName) {

$html = ”;

if(!class_exists(‘SoftDeleteBehavior’)) {
$html .= $this->Form->postLink(__(‘Delete’), array(‘action’ => ‘delete’, $data[$modelName][‘id’]), array(‘class’=>’color-fff’), __(‘Are you sure you want to delete # %s?’, $data[$modelName][‘id’]));
} else {
if(!$this->isActive($data, $modelName)) {
$btn_title = __(‘Retrieve’);
$css_class = ‘btn btn-info’;

$html .= $this->Form->postLink($btn_title, array(‘action’ => ‘undelete’, $data[$modelName][‘id’]), array( ‘class’=>$css_class), __(‘Are you sure you want to retrive # %s?’, $data[$modelName][‘id’]));

$css_class_danger = ‘btn btn-danger’;

$html .= $this->Form->postLink(__(‘Purge Deleted’), array(‘action’ => ‘purge’, $data[$modelName][‘id’]), array( ‘class’=>$css_class_danger), __(‘Are you sure you want to permanently delete a # %s?’, $data[$modelName][‘id’]));
} else {
$html .= $this->Form->postLink(__(‘Delete’), array(‘action’ => ‘delete’, $data[$modelName][‘id’]), array(‘class’=>’color-fff’), __(‘Are you sure you want to delete # %s?’, $data[$modelName][‘id’]));
}
}
return $html;
}
[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *