Search code examples
phpdrupaldrupal-hooksdrupal-blocks

Catch Change / Add / Delete Event for Blocks in Drupal


I need to add some functionality (flush some caches and such) when a Block in Drupal is added, moved, edited or deleted, is there ANY kind of hook for that (or another somewhat Drupal native way) like there is for nodes with hook_nodeapi?

I know there is hook_block but there $op is always list, so its not really any good.


Solution

  • Unfortunately blocks don't have that kind of signalling mechanism. I would use the forms system to add submit callbacks wherever you need a signal for additional work.

    /**
     * Implementation of hook_form_alter().
     */
    function custom_form_alter(&$form, &$form_state, $form_id) {
      // Overview form.
      if ($form_id == 'block_admin_display_form') {
        $form['#submit'][] = 'custom_block_admin_display_form_submit';
      }
      // Individual block configuration form.
      elseif ($form_id == 'block_admin_configure') {
        $form['#submit'][] = 'custom_block_admin_configure_submit';
      }
    }
    
    /**
     * Submit handler for block overview form.
     */
    function custom_block_admin_display_form_submit($form, &$form_state) {
      cache_clear_all();
    }
    
    /**
     * Submit handler for block configuration form.
     */
    function custom_block_admin_configure_form_submit($form, &$form_state) {
      drupal_set_message(t('You have changed a block. Run for the hills!'));
    }
    

    The one downside to this method is that any alternate approach to configuring blocks won't work. If someone builds a custom form outside the block module, or if you are using context or panels to move blocks around it won't help. Of course, since any of those alternate configuration points would also use a form, you can use hook_form_alter() to hack into their submit processes as well.