作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何在 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/
我是一名优秀的程序员,十分优秀!