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.
- Create a new rule
- Add an event that relates to order, in our case "Completeting the checkout process".
- Add a loop. Choose "commerce_order:commerce-line-items" in Data selector. That should provide you with line item objects for the PHP code.
- Add an "Execute custom PHP code" action.
- 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