July 27, 2012 - Comments Off on Drupal commerce, rules, and beyond

Drupal commerce, rules, and beyond

When creating and processing orders with Commerce in Drupal, you will sometimes need to modify or manipulate the data at some stage in the checkout processes. As we've seen in earlier posts you can easily create or modify rules in Drupal to do just about anything. [hook_coffee_init() anyone?]. If you need to manipulate the current order, create a new rule and set it to React on the Completing checkout process event. Now  you will have access to the $commerce_order object and all of its data goodness.

Now that the Commerce Order is in scope we can access it and perform and action on it. We won't worry about setting any conditions for the rule for this example. Create a new Action for the rule and set it to Execute custom PHP code. You will now see that the $commerce_order object is available. You can start manipulating it with code right there in the PHP code block, or pass the $commerce_order object to a custom module. This is the way we chose to do it. Since we needed to do some extra stuff with the data such as compare some of its values with an external database application it seemed to make more sense to create a module with that code and have it accept the $commerce_order object. We were then able to do better and quicker coding and version control with code kept in external files out side of the rule.

To call your function, just enter it in the PHP code block and include the opening and closing PHP tags as per the instructions:

<?php mechmod($commerce_order); ?>

Here is a quick module sample that can accept the $commerce_order object and do something with it. Create these two files in /sites/all/modules/mechmod


name = Mechanism Commerce Infandibulator
description = Do stuff with a $commerce_order object
core = 7.x
version 0.0.1beta


 * function to do stuff with $commerce_order object
function mechmod_commerce_object_raw($commerce_order) {
  if(module_exists('devel')) { // If devel module is enabled, use dpm()
  else {  // otherwise, just print it out

Now enable the module:

% drush en mechmod --yes

(--yes will automatically choose 'yes' for you instead of being prompted by drush to confirm)

Now, whenever you complete the checkout process the whole $commerce_object will be printed out. This isn't terribly pretty, but it is the beginning of being able to see and then access the data in the order and from there to manipulate it.

Happy coding,

Published by: chazcheadle in The Programming Mechanism
Tags: , , ,

Comments are closed.