Drupal commerce

How to manipulate pricing using Order Processor in Commerce 2.x

Highly customizable business logic is the core of any e-commerce solution. For such functionality, Order processor comes in picture which helps us to define flexible pricing with dynamic discounts.

In this article I will walk you through order price manipulation and use of custom adjustment to fulfill complex business logics in Drupal commerce 2.x module.

What is Order Processor?

E-commerce order processing is part of the order refresh process. This is executed on draft orders to ensure that it has up to date adjustments and that its order items are up to date. E-commerce order processing is a part of e-commerce workflow in drupal commerce 2.x.

What are Adjustments in Drupal commerce 2.x compared to Drupal 7?

We know that from Commerce 1.x  each product place in the order was defined as a Line item. In Commerce 2.x, the line item is renamed to Order item, but it only holds purchasable products, wherein Drupal 7 line item was used for shipping costs and discounts.

Order Processor in Commerce 2.x

Let’s fulfill a basic business logic where, if the product has price more than 20$ and quantity less than 10, it should get a complete discount and get that product for free.

For programming business logic, first we will create a custom module named commerce_customization. In that we will create a custom adjustment for the discount feature.

We Create a yml file to initialize the custom adjustment

Now we need to create orderprocessor.php for our custom module as CustomOrderProcessor.php under Src folder of the module.

Code Snippet to set the custom adjustment.


$adjustments[] = new Adjustment([
           'type' => 'custom_adjustment',
           'label' => 'Discounted Price - ' . $product_title,
           'amount' => new Price('-' . $new_adjustment, 'USD'),

Now, we need to set the priority for our custom order processor to be called at first place then the default order processor. For that we need to write services.yml as commerce_customizartions.services.yml

Hence, when we purchase a product having unit price as 10$ and taking in a quantity of 5, our business logic gets applied due to the order processor in our cart.

Order Processor Output

Order processor plays a key role in manipulations of prices and adjustments in Drupal Commerce 2.x for building complex ecommerce portals with programming business logic.

So here we achieved to implement a simple business logic of applying discount for products with quantity less than 10 and base price less than $20 by order processor.

Code Source : https://github.com/chishah92/commerce-customizations