How to add custom operation in Views Bulk Operation.

| | 2 min read

Views bulk operations module is used for performing multiple operations for multiple rows on a view. Here we can have default action on the view configurations and can also add our custom actions as per the requirements. Views bulk operation module reuses and extends Drupal core Action system. Also most of the Drupal core actions are VBO-compatible actions.

The following steps to perform custom actions on the VBO.

1. First we need to define the action for the VBO.

<?php
  /* Implement hook_action_info(). */
    function MYMODULE_action_info() {
      return array(
        'MYMODULE_my_custom_action' => array(
          'type' => 'node',
          'label' => t('Search and replace the text in a field'),
          'behavior' => array('changes_property'),
          'configurable' => FALSE,
          'vbo_configurable' => TRUE,
          'triggers' => array('any'),
        ),
      );
    }
  ?>

2. Next add a VBO configuration form

function mymodule_my_custom_action_views_bulk_operations_form($options) {
  $form = array();
  $form['options'] = array(
    '#type' => 'select', 
    '#title' => t('Choose your options'),
    '#options' => array(
      'Iron Man' => t('abc'),
      'Bat Man' => t('efg'),
      ),
    '#default_value' => !empty($options['options']) ? $options['options'] : '',
  );

  return $form;
}

3. Add a per-bulk configuration form as well

We should return data to be passed to the actual action function, in the submit function so that we can make the action "flexible".

function mymodule_my_custom_action(&$node, $context) {
  $message = t('Node title is %title. Sincerely, %hero', array(
    '%title' => $node->title,
    '%hero' => $context['hero'],
  ));
  drupal_set_message($message);
}

4. Provide Permissions for actions in the VBO

function MYMODULE_action_info() {
    return array(
      'MYMODULE_my_custom_action' => array(
        'type' => 'node',
        'label' => t('Search and replace the text in a field'),
        'permissions' => array('access content', 'administer site configuration'),
        ...
      ),
    );
  }

By the above steps you can see your custom actions and operations in the views.