[Drupal] How to add custom Views Bulk Operation
Views Bulk Operation module is helpful in the cases where we need to perform a particular operation for more than one row in a view. Some of the operations includes deleting multiple contents, publishing/un-publishing contents, change the author of the content, send email etc. In one of our Drupal project I need to perform a action to add a single field for all rows. Drupal provides a hook to declare the required operations and handle extra changes to the bulk operations settings.
These are the default operations along with the module. Now, what if you need some of your operation to be performed other than this? Thats too, is possible. You may read on if you want to know how it can be done.
Step1: Implement hook_actions_info
This hook helps to declares your operation.
For eg:
<?php
function mymodulename_action_info() {
return array(
'my_application_reset_action' => array( // declare the function name to be used. Replace the name with your function name
'type' => 'entity', // can be node,comment etc
'label' => t('Reset Field'), // the name of the operation which is displayed to the user.
'configurable' => FALSE,
'pass rows' => TRUE, //this will ensure that the entire views row is passed as part of the context in your action callback.
),
);
}
?>
Step 2 : Define the operation to be performed
For eg:
<?php
function my_application_reset_action(&$entity, $context = array()) {
$query = db_update('field_data_field_quantity')
->fields(array('field_quantity_value' => '0'))
->condition('entity_id',$entity->nid)
->execute();
}
?gt;
In the above function I am updating a table by setting the value of a field to '0'. You may replace this query with the action you need to perform.
If you just print $entity, you can see, each row in your view is passed as an object to your function definition.
After completing the above steps, if you add a Bulk operation field to your view, you can see your custom operation in its operation list.