Drupal 7 Programmatically Creating a Rule with a Custom Action
Commerce module uses Rules module extensively. Unlike Ubercart where you can just call a hook and receive $account information of the final process once an anonymous user is converted to a Drupal authenticated user, once checkout is complete. With Commerce we have to use Rules to create a custom rule with an action that ultimately executes a callback....Yes, I know....
Here's the example of what we did. Look at the code comments for a better hint of what is going on.
/**
* Implements hook_default_rules_configuration().
*/
function yourmodule_default_rules_configuration() {
$rules = array();
$rule = rules_reaction_rule();
$rule->label = t('After new user is created');
$rule->active = variable_get('mymodule_append_data_to_new_user', TRUE);
$rule
// We use a system event.
->event('user_insert')
// action() is smart enough to know this is a
// custom action that we'll define later.
->action('add_data_to_user_object', array(
'type' => 'user',
));
// Execute after similar rules.
$rule->weight = 10;
// The unique machine name of your rule.
$rules['yourmodule_append_qbo_customer_id_to_new_user'] = $rule;
return $rules;
}
/**
* Implements hook_rules_action_info().
*/
function yourmodule_rules_action_info() {
$defaults = array(
// Defines parameters that are passed to
// your callback.
'parameter' => array(
'account' => array(
'type' => 'user',
'label' => t('User'),
// Tells Rules to save any changes made to $account.
'save' => TRUE,
),
),
'group' => t('User'),
// Rules built-in access.
'access callback' => 'rules_user_integration_access',
);
// The name of our custom action that was defined in
// ji_commerce.rules_defaults.inc.
$actions['add_data_to_user_object'] = $defaults + array(
'label' => t('Insert a new user'),
// Finally, our callback!
'base' => 'yourmodule_action_insert_new_user',
);
return $actions;
}
/**
* Callback: We run QBO calls here. Since with Commerce
* we can't do it within the hook_commerce_checkout_complete().
*/
function yourmodule_action_insert_new_user($account) {
// This change will automatically be saved by Rules.
$account->data['some_id'] = 100;
}
Leave a comment