判断自定义的产品属性是否存在

2.42K 浏览开发笔记产品属性

判断自定义的产品属性是否存在

比如判断color属性是否存在。

<code><?php
namespace Zou\Demo\Helper;
class Custom
{
    /**
     * @var \Magento\Eav\Model\Config
     */
    private $_eavConfig;
 
    /**
     * @param \Magento\Eav\Model\Config $eavConfig
     */
    public function __construct(
        \Magento\Eav\Model\Config $eavConfig
    ) {
        $this->_eavConfig = $eavConfig;
    }
 
    /**
     * Returns true if attribute exists and false if it doesn't exist
     *
     * @param string $field
     * @return bool
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function isProductAttributeExists($field)
    {
        $attr = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $field);
 
        return ($attr && $attr->getId()) ? true : false;
    }

}</code>

在phtml里可以这样调用

$hasColor = $this->helper('Zou\Demo\Helper\Custom')->isProductAttributeExists('color');

 

0