Drupal Commerce: Adjusting Stock from Code

Recently I have been working on a project using Drupal Commerce to build a Jewelry online shop for client. At one point we needed to find a way to adjust the stock of a product that is referenced by another product through the use of Entity Reference field, and unforutnately the current implementation of DC does not provided the needed feature in Rules, hence we had to do it through Code.

After some testing, turned out the stock data is not simply stored in just 1 table (or perhaps there was something that we did wrong? :P), though thanks to the awesome work from Commerce Guys they have already implemented some very useful functions that will ease the pain digging through the data structure. The following steps already assume that you have commerce_stock module installed already.

  1. Create a new rule
  2. Add an event that relates to order, in our case "Completeting the checkout process".
  3. Add a loop. Choose "commerce_order:commerce-line-items" in Data selector. That should provide you with line item objects for the PHP code.
  4. Add an "Execute custom PHP code" action.
  5. Choose Commerce Product. You should see that there is a Commerce Line Item type of variable made available to you. in our case, the we have is $list_item.

The line item object should give you the id and type of the product along with various other information. From there you can use commerce_product_load($product_id) and commerce_stock_adjust($product) to adjust stock in a blink:

<?php

    
global $language;

    if (
$list_item) {

    
// Check if the field was translated
    
$lang = isset( $list_item->commerce_product[$language->language]) ? $language->language LANGUAGE_NONE;

    
// Get the product id from line item ($list_item)
    
$product_id $list_item->commerce_product[$lang][0]['product_id'];

    
// Load product entity
    
$product commerce_product_load($product_id);

    
// Decrease stock by 1
    
commerce_stock_adjust($product, -1);
    }

?>

Apparently Drupal Commerce's commerce_stock module has rules can do all this already out of the box. However if your have products referencing other products that need to adjust the stock all together, this code will come in handy :).

Comments

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <c>, <cpp>, <drupal5>, <drupal6>, <java>, <javascript>, <php>, <python>, <ruby>. The supported tag styles are: <foo>, [foo], [[foo]]. PHP source code can also be enclosed in <?php ... ?> or <% ... %>.
  • Images can be added to this post.

More information about formatting options