Magento – Magento2 – Change customer Group Programatically for guest and logged in users

customer-groupmagento2

I have a form in which when a particular code is given, the customer group should be changed to apply discounts.

I have tried the following code, it changes the customer group. I can see the discounted prices in Product list page as well as Product detail page. But in the cart and checkout process it doesnt apply.

$this->session->setCustomerGroupId("3");

Can someone please help in solving the issue.

Best Answer

$this->session->setCustomerGroupId("3");

This only saves the customer group id in the session (which is temporary). I think in the Checkout, the actual Customers Group ID is used again.

You can set the customers group id (persistent) with the following code:

$this->session->getCustomer()->setGroupId("3")->save();

You have to make sure, that the customer is logged in before. You can check that with the following:

$this->session->isLoggedIn()
Related Topic