drbxr86044 2015-12-23 13:58
浏览 115
已采纳

如何通过Magento 2.0中的属性代码获取产品属性选项

I am trying to retrieve the list of dropdown attributes and check if the value exists (if it does i need to get the value and assign it to the product) and if it doesnt i will have to create it and get its value to assign it to the product.

$attribute = $this->objectManager->create('Magento\Eav\Model\Entity\Attribute');
$attributeId = $attribute->getIdByCode('catalog_product','manufacturer');
$model = $this->objectManager->create('Magento\Catalog\Model\ResourceModel\Eav\Attribute');
$model->load($attributeId);
print_r($model->getFrontendLabel());
  • 写回答

5条回答 默认 最新

  • dongta1824 2016-02-03 17:13
    关注

    Following Magento 2 guidelines, you should not use ObjectManager by yourself. Instead, you must use dependency injection. More info here

    In your Block/Controller/Helper..., create a constructor and inject \Magento\Catalog\Model\Product\Attribute\Repository class. For example :

    /**
     * @var \Magento\Catalog\Model\Product\Attribute\Repository $_productAttributeRepository
     */
    protected $_productAttributeRepository;
    
    /**
     * @param \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository
     */
    public function __construct(\Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository)
    {
        $this->_productAttributeRepository = $productAttributeRepository;
    }
    

    Then, in your dedicated method, you want to call (PHPDoc added for clarity) :

    /** @var \Magento\Eav\Api\Data\AttributeOptionInterface[] $manufacturerOptions */
    $manufacturerOptions = $this->_productAttributeRepository->get('manufacturer')->getOptions();
    

    You can now get options values and labels this way :

    foreach ($manufacturerOptions as $manufacturerOption) {
        $manufacturerOption->getValue();  // Value
        $manufacturerOption->getLabel();  // Label
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(4条)

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题