gpt4 book ai didi

attributes - 如何在 Magento 2 中以编程方式将现有属性添加到属性集

转载 作者:行者123 更新时间:2023-12-05 07:32:14 28 4
gpt4 key购买 nike

如何在 Magento 2 中以编程方式将一些现有属性添加到新属性集中?

最佳答案

在 magento 2 中,已经创建了 color & manufactor 属性,但是默认情况下这两个属性没有分配给默认属性集。所以,我们可以这样做。然后它会在模块安装时将这两个属性分配给默认属性。

<?php
namespace Vendor\Module\Setup;

use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;

class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
private $categorySetupFactory;

public function __construct(EavSetupFactory $eavSetupFactory, \Magento\Catalog\Setup\CategorySetupFactory $categorySetupFactory)
{
$this->eavSetupFactory = $eavSetupFactory;
$this->categorySetupFactory = $categorySetupFactory;
}

public function install(ModuleDataSetupInterface $setup, ModuleContextInterface $context)
{
try {
/**
* @var \Magento\Eav\Setup\EavSetup
*/
$eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

/**
* @var \Magento\Catalog\Setup\CategorySetup
*/
$categorySetup = $this->categorySetupFactory->create(['setup' => $setup]);

$entityTypeId = $categorySetup->getEntityTypeId(\Magento\Catalog\Model\Product::ENTITY);
$attributeSetId = $categorySetup->getDefaultAttributeSetId($entityTypeId); // get default attribute set id
$attrGroupId = $categorySetup->getDefaultAttributeGroupId($entityTypeId, $attributeSetId); // get default attribute group id (in my case, it returns id of 'Product Details' group)

$colorAttr = $eavSetup->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'color');
if($colorAttr) {
$eavSetup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attrGroupId,
'color',
null
);
}

$manufacturerAttr = $eavSetup->getAttribute(\Magento\Catalog\Model\Product::ENTITY, 'manufacturer');
if($manufacturerAttr) {
$eavSetup->addAttributeToGroup(
$entityTypeId,
$attributeSetId,
$attrGroupId,
'manufacturer',
null
);
}

} catch (NoSuchEntityException $e) {
return;
} catch (\Exception $e) {
return;
}
}

关于attributes - 如何在 Magento 2 中以编程方式将现有属性添加到属性集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51361165/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com