Переместить атрибут существующей категории в новую группу

magento.stackexchange https://magento.stackexchange.com/questions/11259

  •  16-10-2019
  •  | 
  •  

Вопрос

Я в основном хочу переместить атрибут существующей категории в недавно созданную группу в моем файле настройки. Я ожидал, что это сработает:

$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();

Он добавляет новый атрибут в группу, как и ожидалось, но не перемещает Meta_title в новой группе. Я полагаю, я использую неправильный код. Любая помощь очень ценится.

Это было полезно?

Решение

Вы можете перенести атрибут MAGE_CATALOG_MODEL_CATEGORY в новую группу через сценарий установщика, выполнив следующую логику.

Предварительные условия:

  • Атрибут каталога должен уже существовать
  • Группа, в которую вы перемещаете атрибут, должна уже существовать

Единственные изменения здесь, которые должны быть необходимы, - это значения двух верхних переменных ($ attribute_code и $ 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();

Если мы внимательно прочитаем этот код, можно увидеть, что все, что действительно происходит здесь, это то, что мы находим идентификатор группы и обновляем attribute_group_id колонка в eav_entity_attribute Таблица, для записи, которая содержит наш атрибут. Лично мне легче просто сделать это непосредственно в базе данных. Однако вы спросили, как сделать это через сценарий установщика;)

Другие советы

Из памяти я думаю, что это что -то вроде -

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

Не проверял это, хотя извините.

Делать это правильно

Вот как вы делаете это для атрибутов продукта, и это должно работать, изменяя идентификатор типа объекта:

$setup = new Mage_Catalog_Model_Resource_Setup('core_setup');

Загрузите свой атрибут:

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

Получить идентификатор набора атрибутов (если у вас есть несколько наборов атрибутов, вам придется сделать это для каждого набора атрибутов):

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

Получить идентификатор группы атрибутов (в этом случае я перемещаю атрибут на вкладку «Видимость»):

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

И, наконец, позвоните addAttributeToSet:

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

Оказывается, это невозможно сделать с существующей функцией через файл настройки.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с magento.stackexchange
scroll top