Create and Add Attribute Group with Attributes to All Attribute Sets in Magento 1

attribute-setproduct-attribute

I need to create and add an attribute group with 6 attributes to all attributes sets in an existing install.

I have found a script for creating an attribute group, this works great, but this can not add attributes to this new group.

Any help will be highly appreciated.

This script works great for adding an attribute group, but how can I add 6 attributes to a new group:

<?php
//enable errors to see if something is wrong
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
//include Mage.php
define('MAGENTO_ROOT', getcwd());
$mageFilename = MAGENTO_ROOT . '/app/Mage.php';
require_once $mageFilename;
//tell magento that you are running on developer mode, for additional error messages (if any)
Mage::setIsDeveloperMode(true);
//instantiate the application
Mage::app();
//get the type ID of the product - you will need it later
$entityTypeId = Mage::getModel('catalog/product')->getResource()->getTypeId();
//get all attribute sets
$sets = Mage::getModel('eav/entity_attribute_set')
    ->getResourceCollection()
    //filter only sets for products - that's why you needed the product type ID
    ->addFilter('entity_type_id', $entityTypeId);
//loop through all the sets
foreach ($sets as $set){
    //create an attribute group instance
    $modelGroup = Mage::getModel('eav/entity_attribute_group');
    //set the group name
    $modelGroup->setAttributeGroupName('Some group name here') //change group name
        //link to the current set
        ->setAttributeSetId($set->getId())
        //set the order in the set
        ->setSortOrder(100);
    //save the new group
    $modelGroup->save();
}

Best Answer

It's a lot easier to do it via setup script. Here is an example:

// Add new Attribute group
$groupName = 'My Attr Group';
$entityTypeId = $installer->getEntityTypeId('catalog_product');
$attributeSetId = $installer->getDefaultAttributeSetId($entityTypeId);
$installer->addAttributeGroup($entityTypeId, $attributeSetId, $groupName, 100);
$attributeGroupId = $installer->getAttributeGroupId($entityTypeId, $attributeSetId, $groupName);

// Add existing attribute to group
$attributeId = $installer->getAttributeId($entityTypeId, ATTRIBUTE_CODE);
$installer->addAttributeToGroup($entityTypeId, $attributeSetId, $attributeGroupId, $attributeId, null);

Note: $installer variable is instance of Mage_Eav_Model_Entity_Setup class. You can look there for further reference. You can also look in app/code/core/Mage/Catalog/sql/catalog_setup folder for some more examples.

Related Topic