Customer Group Management – Magento Programmatically Create and Update Customer Groups

customer-group

I have used the below code for create the customer group programmatically, it works well.
But i need that if the same customer group exist it should update the values, instead of creating new one with same name.

$customer_group=Mage::getModel('customer/group');
$customer_group->setCode($typename.'_'.$id);
$customer_group->setTaxClassId(3);
$customer_group->save();

Best Answer

$code = 'Your code here';
$collection = Mage::getModel('customer/group')->getCollection() //get a list of groups
    ->addFieldToFilter('customer_group_code', $code);// filter by group code
$group = Mage::getModel('customer/group')->load($collection->getFirstItem()->getId()); //load the first group with the required code - this may not be neede but it's a good idea in order to make magento dispatch all events and call all methods that usually calls when loading an object

$group->setCode($code); //set the code
$group->setTaxClassId(3); //set tax class
$group->save(); //save group

In this approach above, If the group with a certain code exists you will get it in the $group variable. If it doesn't exist, you will simply get in $group an empty instance of the customer group model.

Related Topic