Jump to content

Creating a cart rule programmatically for specific customer group


Recommended Posts

HI there, 

I'm creating a module to handle promotion through customer group and I need to create cart rule for each group to let them having free delivery. I've created cart rule and specified group restriction but I'm unable to specify the concerned group id. Any idea ? 

$rule = new CartRule();

$rule->name =  array (Configuration::get('PS_LANG_DEFAULT') => "Free liv for newbies"); 
$rule->date_from = "2019-12-12";
$rule->date_to = "2025-12-12";
$rule->quantity = 1000;
$rule->minimum_amount = 250; 
$rule->free_shipping = 1;
$rule->group_restriction = 1; // How to specify the concerned group id ?
$rule->add();

Thanks

Link to comment
Share on other sites

  • 3 years later...

Hey.

Bumping up this thread just because I was looking into coupon creation myself and just came upon this topic.

In case anyone finds it useful, the following would be the method to specify which groups your cart rule is restricted to.

 

Once we've added our coupon, we need to take note of our cart rule ID. We can simply call the object and the item inside ($rule->id) or declare a variable for later use, if that fits your code better:   

$cart_rule_id = $rule->id

Now, to specify the groups, we need to add them to the _group_restriction table in your database (this refers to Prestashop 1.7). To do so we declare a variable with the group or groups we want to restrict the cart rule to, eg:

$restricted_groups = 3;

or 

$restricted_groups = [3,5,12];

 

If there's just one ID in the variable, we call the DB class and insert the record, if the variable is an array of IDs we loop through it and do the same for each one:

                Db::getInstance()->execute('
                    INSERT INTO 
                        '._DB_PREFIX_.'cart_rule_group (id_cart_rule, id_group)
                    VALUES ('.(int)$cart_rule_id.', '.(int)$id_group_restriction.')
                    ');

OR

foreach($restricted_groups as $group) {

                Db::getInstance()->execute('
                    INSERT INTO 
                        '._DB_PREFIX_.'cart_rule_group (id_cart_rule, id_group)
                    VALUES ('.(int)$cart_rule_id.', '.(int)$group.')
                    ');
}

 

That should do the trick.
 

 

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...