Pregunta

Básicamente, quiero mover un atributo de categoría existente a un grupo recién creado en mi archivo de configuración. Esta es la forma en que esperaba que funcionara:

$installer = new Mage_Eav_Model_Entity_Setup('core_setup');
$installer->startSetup();
$entityTypeId = 'catalog_category';

$installer->addAttribute($entityTypeId, 'my_attribute', array(
'group'         => 'Adams Group',
'input'         => 'text',
'type'          => 'varchar',
'label'         => 'My Attribute Label',
'visible'       => 1,
'required'      => 0,
'user_defined' => 1,
'global'        => Mage_Catalog_Model_Resource_Eav_Attribute::SCOPE_STORE
));

$installer->updateAttribute($entityTypeId, 'meta_title', array(
'group' => 'Adams Group'
));

$installer->endSetup();

Agrega el nuevo atributo al grupo como se esperaba, pero no mueve Meta_Title en el nuevo grupo. Supongo que estoy usando el código incorrecto. Cualquier ayuda muy apreciada.

¿Fue útil?

Solución

Puede mover un atributo de Mage_Catalog_Model_Category a un nuevo grupo, a través de un script de instalador, realizando la siguiente lógica.

Prerrequisitos:

  • El atributo del catálogo ya debe existir
  • El grupo al que está moviendo el atributo ya debe existir

Los únicos cambios aquí que deberían ser necesarios son los valores de las dos variables principales ($ attribute_code y $ attribute_group_name).

<?php
/**
 * Moving a category attribute from one group to another.
 */

$this->startSetup();

$attribute_code       = 'your_attribute_code'; // Catalog Category attribute we want to move
$attribute_group_name = 'Some Group Name';     // Group we want to move it to (must already exist).

// Some necessary objects for this operation.
$conn  = $this->getConnection();
$read  = Mage::getSingleton('core/resource')->getConnection('core_read');
$write = Mage::getSingleton('core/resource')->getConnection('core_write');

// Fetch the id of the attribute we want to move
$attribute_id = Mage::getModel('eav/entity_attribute')->loadByCode('catalog_category', $attribute_code)->getId();

// Fetch the 'entity_type_id' for a Magento category. 
$entity_type_id = Mage::getModel('eav/entity_type')->loadByCode('catalog_category')->getId();

// Fetch the 'attribute_set_id' for Magento categories (unlike products, there's only one for categories)
$tbl = $conn->getTableName('eav_attribute_set');
$sql = "SELECT `attribute_set_id` FROM `{$tbl}` WHERE `entity_type_id` = :entity_type_id";
$bnd = array('entity_type_id' => $entity_type_id);

$attribute_set_id = $read->fetchCol($sql, $bnd);
$attribute_set_id = $attribute_set_id[0];

// Now we'll need the 'attribute_group_id' for the group we want to move the attribute TO
$tbl = $conn->getTableName('eav_attribute_group');
$sql = "SELECT `attribute_group_id` FROM `{$tbl}` WHERE `attribute_set_id` = :attribute_set_id AND `attribute_group_name` = :attribute_group_name";
$bnd = array('attribute_set_id' => $attribute_set_id, 'attribute_group_name' => $attribute_group_name);

$attribute_group_id = $read->fetchCol($sql, $bnd);
$attribute_group_id = $attribute_group_id[0];

// We now have all the information we need to move our attribute to the new group.
$tbl = $conn->getTableName('eav_entity_attribute');
$sql = "UPDATE `{$tbl}` SET `attribute_group_id` = :attribute_group_id WHERE `entity_type_id` = :entity_type_id AND `attribute_set_id` = :attribute_set_id AND `attribute_id` = :attribute_id";
$bnd = array('attribute_group_id' => $attribute_group_id, 'entity_type_id' => $entity_type_id, 'attribute_set_id' => $attribute_set_id, 'attribute_id' => $attribute_id);

$write->query($sql, $bnd);

$this->endSetup();

Si leemos este código cuidadosamente, uno verá que todo lo que realmente está sucediendo aquí es que estamos encontrando la identificación del grupo y actualizando el attribute_group_id columna en el eav_entity_attribute tabla, para el registro que contiene nuestro atributo. Personalmente, me resulta más fácil hacer esto directamente en la base de datos. Sin embargo, preguntó cómo hacer esto a través de un script de instalador;)

Otros consejos

De memoria, creo que es algo así como -

$installer->addAttributeToGroup($entityTypeId, $attributeSetId, array('group' => 'Adams Group'), 'meta_title');

No lo probé aunque lo siento.

Haciéndolo de la manera correcta

Así es como lo hace para los atributos del producto, y debería funcionar cambiando la ID de tipo de entidad:

$setup = new Mage_Catalog_Model_Resource_Setup('core_setup');

Cargue su atributo:

$attribute = Mage::getModel('eav/entity_attribute')
    ->loadByCode('catalog_product', 'my_attribute');

Obtenga ID de conjunto de atributos (si tiene múltiples conjuntos de atributos, tendrá que hacer esto para cada conjunto de atributos):

$setId = $setup->getAttributeSetId(Mage_Catalog_Model_Product::ENTITY, 'Default');

Obtener ID de grupo de atributos (en este caso, estoy moviendo un atributo a la pestaña Visibilidad):

$groupId = $setup->getAttributeGroupId(Mage_Catalog_Model_Product::ENTITY, $setId, 'Visibility');

Y por último, llama addAttributeToSet:

$setup->addAttributeToSet(Mage_Catalog_Model_Product::ENTITY, $setId, $groupId, $attribute->getId());

Resulta que esto no es posible con una función existente a través del archivo de configuración.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a magento.stackexchange
scroll top