Magento 2 Create & Apply Shopping Cart Rule Programmatically

In Magento 2, you will need to use Repositories to create/update/save entities. In Magento core part, still there are few issues with repositories for specific entities like for SalesRule functionality, so here we will see how to do this directly via Magento model.

You need to inject SalesRule factory object in your class constructor as following:

...
protected $ruleFactory

public function __construct(\Magento\SalesRule\Model\RuleFactory $ruleFactory) {
    $this->rulesFactory = $ruleFactory;
}
...

After this constructor injection, you need to do the following with the rule data which you want to create as following:

a) Add the rule data to the following array structure.

c) Assign this array data to the rule model and save the model which will create the rule with data provided.

$ruleData = [
            "name" => "Buy 2 pants and get 3rd free",
            "description" => "Buy 2 pants and get 3rd free",
            "from_date" => null,
            "to_date" => null,
            "uses_per_customer" => "0",
            "is_active" => "1",
            "stop_rules_processing" => "0",
            "is_advanced" => "1",
            "product_ids" => null,
            "sort_order" => "0",
            "simple_action" => "buy_x_get_y",
            "discount_amount" => "1.0000",
            "discount_qty" => null,
            "discount_step" => "2",
            "apply_to_shipping" => "0",
            "times_used" => "0",
            "is_rss" => "1",
            "coupon_type" => "NO_COUPON",
            "use_auto_generation" => "0",
            "uses_per_coupon" => "0",
            "simple_free_shipping" => "0",
            "customer_group_ids" => [0, 1, 2, 3],
            "website_ids" => [1],
            "coupon_code" => null,
            "store_labels" => [],
            "conditions_serialized" => '',
            "actions_serialized" => ''
        ];

$ruleModel = $this->ruleFactory->create();
$ruleModel->setData($ruleData);
$ruleModel->save();

Leave a Reply