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();
up vote 8 down vote accepted
$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.

I also needed to create a customer group programmatically. In my case I used an update script to do so. Code as follow:

 /* @var $installer Mage_Customer_Model_Resource_Setup */
$installer = $this;

$installer->startSetup();

$installer->getConnection()->insert($installer->getTable('customer/customer_group'), array(
    'customer_group_code'   => 'YOUR_CUSTOMER_GROUP',
    'tax_class_id'          => 3
));

$installer->endSetup();

To create Customer Group try below code.

<?php
require_once 'app/Mage.php';
umask(0);
/* not Mage::run(); */
Mage::app('default');

//Create Customer Group 
Mage::getSingleton('customer/group')->setData(
     array('customer_group_code' => 'Partners','tax_class_id' => 5))
->save(); 
?>

To edit customer group

$data=Mage::getSingleton('customer/group')->load($customer_group_id);
print_r($data);

The common way to do this is by creating an instance of the model and attempt to load. Updating and setting initial data is the same regardless of whether the group existed or not.

This does not require any direct SQL or the creation of a collection:

$code = $typename.'_'.$id;

// Create model and attempt to load
$customerGroup = Mage::getModel('customer/group');
$customerGroup->load($code,'customer_group_code');

// If does not exist, set code
if (!$customerGroup->getId()) {
    $customerGroup->setCode($code);
}

// Set data and save whether existed or not
$customerGroup->setTaxClassId(3);
$customerGroup->save();

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.