Error message

The spam filter installed on this site is currently unavailable. Per site policy, we are unable to accept new submissions until that problem is resolved. Please try resubmitting the form in a couple of minutes.

Drupal - "Hooking" into the Deletion of a View

Category: 

Today I stumbled upon the need to do something I've never done before in Drupal. I needed a hook to run some custom code when a View was deleted. First, I checked out the list of Views Hooks and didn't find any hooks that appeared to be able to get the job done.

After a bit of Googling and chatting in #drupal-support on IRC, I was directed to this old closed issue. From my understanding, the delete hook doesn't exist and it  sounds like it won't be existing anytime soon. What can we do? Well never fear, Drupal is here.

One way we could do this would be to use hook_form_alter(). Since a View is most often deleted through the UI, we can use this as our spot to "hook" into the deletion. If you recall, whenever we are about to delete a View through the UI, we are presented with a confirmation screen before actually deleting the View. Luckily this confirmation screen is a form, so we can use some form alterations for the job.

In our custom module, we'll implement the form alteration hook to append a custom submit handler onto the delete confirmation form. That way when the form is submitted to delete the View, our custom code will be executed.

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'ctools_export_ui_delete_confirm_form') {
    $form['#submit'][] = 'my_module_views_deletion_handler';
  }
}

/**
 * Submission handler for the deletion of a View.
 */
function my_module_views_deletion_handler($form, &$form_state) {
  if ($form_state['plugin']['schema'] == 'views_view') {
    // Add custom code here...
    drupal_set_message('Holy smokes, you deleted a View!');
  }
}

Notice the form id is for a ctools form. That means our submission handler needs to check the ctools plugin schema to make sure we are only acting on the deletion of a View, and not any other ctools object (i.e. Panels).

One big assumption is being made here, and that is the View will be deleted through the Views UI. This code will not cover other times when a View is deleted (i.e. during the uninstallation of a module that provided its own default Views).

If that assumption doesn't bother your needs, then this code should work well for you.

Add new comment