Magento2-以编程方式添加产品属性选项


32

在M2中以编程方式添加产品属性选项的正确(官方)方法是什么?例如manufacturer产品属性。显然,现有选项将与“管理员”标题值匹配。

Answers:


55

这是我想出的处理属性选项的方法。助手类:

<?php
namespace My\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
     */
    protected $attributeRepository;

    /**
     * @var array
     */
    protected $attributeValues;

    /**
     * @var \Magento\Eav\Model\Entity\Attribute\Source\TableFactory
     */
    protected $tableFactory;

    /**
     * @var \Magento\Eav\Api\AttributeOptionManagementInterface
     */
    protected $attributeOptionManagement;

    /**
     * @var \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory
     */
    protected $optionLabelFactory;

    /**
     * @var \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory
     */
    protected $optionFactory;

    /**
     * Data constructor.
     *
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository
     * @param \Magento\Eav\Model\Entity\Attribute\Source\TableFactory $tableFactory
     * @param \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement
     * @param \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory
     * @param \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Catalog\Api\ProductAttributeRepositoryInterface $attributeRepository,
        \Magento\Eav\Model\Entity\Attribute\Source\TableFactory $tableFactory,
        \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
        \Magento\Eav\Api\Data\AttributeOptionLabelInterfaceFactory $optionLabelFactory,
        \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory
    ) {
        parent::__construct($context);

        $this->attributeRepository = $attributeRepository;
        $this->tableFactory = $tableFactory;
        $this->attributeOptionManagement = $attributeOptionManagement;
        $this->optionLabelFactory = $optionLabelFactory;
        $this->optionFactory = $optionFactory;
    }

    /**
     * Get attribute by code.
     *
     * @param string $attributeCode
     * @return \Magento\Catalog\Api\Data\ProductAttributeInterface
     */
    public function getAttribute($attributeCode)
    {
        return $this->attributeRepository->get($attributeCode);
    }

    /**
     * Find or create a matching attribute option
     *
     * @param string $attributeCode Attribute the option should exist in
     * @param string $label Label to find or add
     * @return int
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function createOrGetId($attributeCode, $label)
    {
        if (strlen($label) < 1) {
            throw new \Magento\Framework\Exception\LocalizedException(
                __('Label for %1 must not be empty.', $attributeCode)
            );
        }

        // Does it already exist?
        $optionId = $this->getOptionId($attributeCode, $label);

        if (!$optionId) {
            // If no, add it.

            /** @var \Magento\Eav\Model\Entity\Attribute\OptionLabel $optionLabel */
            $optionLabel = $this->optionLabelFactory->create();
            $optionLabel->setStoreId(0);
            $optionLabel->setLabel($label);

            $option = $this->optionFactory->create();
            $option->setLabel($optionLabel);
            $option->setStoreLabels([$optionLabel]);
            $option->setSortOrder(0);
            $option->setIsDefault(false);

            $this->attributeOptionManagement->add(
                \Magento\Catalog\Model\Product::ENTITY,
                $this->getAttribute($attributeCode)->getAttributeId(),
                $option
            );

            // Get the inserted ID. Should be returned from the installer, but it isn't.
            $optionId = $this->getOptionId($attributeCode, $label, true);
        }

        return $optionId;
    }

    /**
     * Find the ID of an option matching $label, if any.
     *
     * @param string $attributeCode Attribute code
     * @param string $label Label to find
     * @param bool $force If true, will fetch the options even if they're already cached.
     * @return int|false
     */
    public function getOptionId($attributeCode, $label, $force = false)
    {
        /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
        $attribute = $this->getAttribute($attributeCode);

        // Build option array if necessary
        if ($force === true || !isset($this->attributeValues[ $attribute->getAttributeId() ])) {
            $this->attributeValues[ $attribute->getAttributeId() ] = [];

            // We have to generate a new sourceModel instance each time through to prevent it from
            // referencing its _options cache. No other way to get it to pick up newly-added values.

            /** @var \Magento\Eav\Model\Entity\Attribute\Source\Table $sourceModel */
            $sourceModel = $this->tableFactory->create();
            $sourceModel->setAttribute($attribute);

            foreach ($sourceModel->getAllOptions() as $option) {
                $this->attributeValues[ $attribute->getAttributeId() ][ $option['label'] ] = $option['value'];
            }
        }

        // Return option ID if exists
        if (isset($this->attributeValues[ $attribute->getAttributeId() ][ $label ])) {
            return $this->attributeValues[ $attribute->getAttributeId() ][ $label ];
        }

        // Return false if does not exist
        return false;
    }
}

然后,在同一个类中或通过依赖注入将其包括在内,您可以通过调用来添加或获取选项ID createOrGetId($attributeCode, $label)

例如,如果你注入My\Module\Helper\Data$this->moduleHelper,那么你可以拨打:

$manufacturerId = $this->moduleHelper->createOrGetId('manufacturer', 'ABC Corp');

如果“ ABC Corp”是现有制造商,它将提取该ID。如果没有,它将添加它。

2016-09-09更新: Per Ruud N.,原始解决方案使用CatalogSetup,导致从Magento 2.1开始出现错误。修订后的解决方案绕过该模型,显式创建选项和标签。它应该适用于2.0+。


3
就像您将要获得的一样正式。所有的查找和选项添加都通过核心Magento。我的课程只是这些核心方法的包装,使它们更易于使用。
Ryan Hoerr

1
嗨,瑞安(Ryan),您不应该在该选项上设置值,这是magento所使用的内部ID,我很难找到一种方法,如果将值设置为带有前导数字(例如'123 abc corp')的字符串值,则会导致由于实施的一些严重问题 Magento\Eav\Model\ResourceModel\Entity\Attribute::_processAttributeOptions。自己看看,如果您$option->setValue($label);从代码中删除该语句,它将保存该选项,然后在您获取它时,Magento将从eav_attribute_option表上的自动增量返回值。
quickshiftin

2
如果将其添加到foreach函数中,则在第二次迭代中,我将收到错误消息“ Magento \ Eav \ Model \ Entity \ Attribute \ OptionManagement :: setOptionValue()必须为字符串类型,给定对象”
JELLEJ

1
是的,此代码不起作用
Sourav

2
@JELLEJ如果遇到问题Uncaught TypeError:传递给Magento \ Eav \ Model \ Entity \ Attribute \ OptionManagement :: setOptionValue()的参数3必须为字符串类型,在foreach函数中给定的对象,然后更改$ option-> setLabel( $ optionLabel); 到$ option-> setLabel($ label); 在第102行
Nadeem0035

11

在Magento 2.1.3上测试。

我没有找到任何可行的方法来立即创建带有选项的属性。因此,首先我们需要创建一个属性,然后为其添加选项。

插入以下类\ Magento \ Eav \ Setup \ EavSetupFactory

 $setup->startSetup();

 /** @var \Magento\Eav\Setup\EavSetup $eavSetup */
 $eavSetup = $this->eavSetupFactory->create(['setup' => $setup]);

创建新属性:

$eavSetup->addAttribute(
    'catalog_product',
    $attributeCode,
    [
        'type' => 'varchar',
        'input' => 'select',
        'required' => false,
        ...
    ],
);

添加自定义选项。

函数addAttribute不会返回任何有用的东西,将来可以使用。因此,在创建属性后,我们需要自己检索属性对象。重要!我们需要它,因为函数仅期望使用attribute_id,但不想使用attribute_code

在这种情况下,我们需要获取attribute_id并将其传递给属性创建函数。

$attributeId = $eavSetup->getAttributeId('catalog_product', 'attribute_code');

然后我们需要按照magento期望的方式生成options数组:

$options = [
        'values' => [
        'sort_order1' => 'title1',
        'sort_order2' => 'title2',
        'sort_order3' => 'title3',
    ],
    'attribute_id' => 'some_id',
];

例如:

$options = [
        'values' => [
        '1' => 'Red',
        '2' => 'Yellow',
        '3' => 'Green',
    ],
    'attribute_id' => '32',
];

并将其传递给功能:

$eavSetup->addAttributeOption($options);

addAttribute的第三个参数可以采用数组参数['option']
DWils

10

使用Magento \ Eav \ Setup \ EavSetupFactory甚至\ Magento \ Catalog \ Setup \ CategorySetupFactory类都可能导致以下问题:https : //github.com/magento/magento2/issues/4896

您应该使用的类:

protected $_logger;

protected $_attributeRepository;

protected $_attributeOptionManagement;

protected $_option;

protected $_attributeOptionLabel;

 public function __construct(
    \Psr\Log\LoggerInterface $logger,
    \Magento\Eav\Model\AttributeRepository $attributeRepository,
    \Magento\Eav\Api\AttributeOptionManagementInterface $attributeOptionManagement,
    \Magento\Eav\Api\Data\AttributeOptionLabelInterface $attributeOptionLabel,
    \Magento\Eav\Model\Entity\Attribute\Option $option
  ){
    $this->_logger = $logger;
    $this->_attributeRepository = $attributeRepository;
    $this->_attributeOptionManagement = $attributeOptionManagement;
    $this->_option = $option;
    $this->_attributeOptionLabel = $attributeOptionLabel;
 }

然后在函数中执行以下操作:

 $attribute_id = $this->_attributeRepository->get('catalog_product', 'your_attribute')->getAttributeId();
$options = $this->_attributeOptionManagement->getItems('catalog_product', $attribute_id);
/* if attribute option already exists, remove it */
foreach($options as $option) {
  if ($option->getLabel() == $oldname) {
    $this->_attributeOptionManagement->delete('catalog_product', $attribute_id, $option->getValue());
  }
}

/* new attribute option */
  $this->_option->setValue($name);
  $this->_attributeOptionLabel->setStoreId(0);
  $this->_attributeOptionLabel->setLabel($name);
  $this->_option->setLabel($this->_attributeOptionLabel);
  $this->_option->setStoreLabels([$this->_attributeOptionLabel]);
  $this->_option->setSortOrder(0);
  $this->_option->setIsDefault(false);
  $this->_attributeOptionManagement->add('catalog_product', $attribute_id, $this->_option);

1
谢谢,您是正确的。我已经相应更新了答案。注意$attributeOptionLabel$option是ORM类;您不应该直接注射它们。正确的方法是注入其工厂类,然后根据需要创建一个实例。另请注意,您并非始终使用API​​数据接口。
Ryan Hoerr

3
嗨@Rudd,请看我对Ryan答案的评论。您不想调用该表,$option->setValue()因为它是针对表的内部magento option_id字段的eav_attribute_option
quickshiftin

谢谢。这也是我发现的。将相应地编辑我的答案。
Ruud N.

0

对于Magento 2.3.3,我发现您可以采用Magento DevTeam方法。

  • 添加补丁
bin/magento setup:db-declaration:generate-patch Vendor_Module PatchName
  • 将CategorySetupFactory添加到构造函数
public function __construct(
        ModuleDataSetupInterface $moduleDataSetup,
        Factory $configFactory
        CategorySetupFactory $categorySetupFactory
    ) {
        $this->moduleDataSetup = $moduleDataSetup;
        $this->configFactory = $configFactory;
        $this->categorySetupFactory = $categorySetupFactory;
}
  • 在apply()函数中添加属性

    public function apply()
    {
        $categorySetup = $this->categorySetupFactory->create(['setup' => $this->moduleDataSetup]);
    
        $categorySetup->addAttribute(
            \Magento\Catalog\Model\Product::ENTITY,
            'custom_layout',
            [
                'type' => 'varchar',
                'label' => 'New Layout',
                'input' => 'select',
                'source' => \Magento\Catalog\Model\Product\Attribute\Source\Layout::class,
                'required' => false,
                'sort_order' => 50,
                'global' => \Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_STORE,
                'group' => 'Schedule Design Update',
                'is_used_in_grid' => true,
                'is_visible_in_grid' => false,
                'is_filterable_in_grid' => false
            ]
        );
    }
    

嗯,我只是发现我想将此答案添加到其他问题中。我将在这里居住并在此处添加对此答案的引用。我希望可以。这也是这个问题的部分答案:)
embed0

-4

这不是答案。只是一种解决方法。

假设您可以使用浏览器访问Magento Backend,并且您位于编辑属性页上(URL看起来像admin / catalog / product_attribute / edit / attribute_id / XXX / key ..)

转到浏览器控制台(Chrome上为CTRL + SHIFT + J),并在更改数组mimim之后粘贴以下代码。

$jq=new jQuery.noConflict();
var mimim=["xxx","yyy","VALUES TO BE ADDED"];
$jq.each(mimim,function(a,b){
$jq("#add_new_option_button").click();
$jq("#manage-options-panel tbody tr:last-child td:nth-child(3) input").val(b);
});

-在Magento 2.2.2上测试

详细文章-https://tutes.in/how-to-manage-magento-2-product-attribute-values-options-using-console/


1
这是一个糟糕的长期解决方案。您不能可靠地期望这些选择器保持不变。如果它确实按预期工作,则这是最好的解决方法。
domdambrogia '18

@domdambrogia同意。这是一种解决方法。
th3pirat3 '18
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.