Magento – Magento 2: how to get the product attribute option label instead of option value in admin grid in custom module

magento-2.1.1module

I want to show product attribute option label instead of option value in admin grid in custom module?

Can any one help me in this?

In magento 1 I get this suggestion and same I want in magento 2.

below is the file that show static status in admin grid and I want to retrieve product attribute options and values in admin grid:-

namespace Company\Module\Model;

    class Probore
    {
        /**#@+
         * Module Probore values
         */
        const STATUS_NEW = 1;    
        const STATUS_PROCESSING = 2;        
        const STATUS_COMPLETED = 3;

        /**
         * Retrieve option array
         *
         * @return string[]
         */
        public static function getOptionArray()
        {
            return [self::STATUS_NEW => __('New'),
                self::STATUS_PROCESSING => __('Processing'),
                self::STATUS_COMPLETED => __('Completed')];
        }

        /**
         * Retrieve option array with empty value
         *
         * @return string[]
         */
        public function getAllOptions()
        {
            $result = [];

            foreach (self::getOptionArray() as $index => $value) {
                $result[] = ['value' => $index, 'label' => $value];
            }

            return $result;
        }

        /**
         * Retrieve option text by option value
         *
         * @param string $optionId
         * @return string
         */
        public function getOptionText($optionId)
        {
            $options = self::getOptionArray();

            return isset($options[$optionId]) ? $options[$optionId] : null;
        }
    }

How to retrieve attribute and assign in the admin grid so option label is visible in admin grid.

I am using below code:-

namespace Company\Module\Model;

//use Psr\Log\LoggerInterface;

class Probore
{
    /**
     * @var \Company\Module\Helper\Data
     */
    protected $_helper;

    protected $_logLoggerInterface;
    protected $_context;


    public function __construct(       
        \Magento\Backend\Block\Template\Context $context,
        //LoggerInterface $logLoggerInterface,
        \Company\Module\Helper\Data $helper
    ) { 
        //$this->_logLoggerInterface = $logLoggerInterface;
        $this->_helper = $helper;
        $this->_context = $context;
        parent::__construct($context);      
    }   

    public static function getOptionArray()
    {
        $result = array (
            '4' => '0.5',
            '6' => '0.6',
        );      
        return $result;        
    }

    /**
     * Retrieve option array with empty value
     *
     * @return string[]
     */
    public function getOptions()
    {
        $data = $this->_helper->getAttributeLabel();
        $res = [];
        foreach ($data as $index => $value) {
           $res[] = ['value' => $value['value'], 'label' => $value['label']];
        }
        return $res;
    }

    public function getOptionText($optionId)
    {
        $options = self::getOptionArray();

        return isset($options[$optionId]) ? $options[$optionId] : null;
    }
}

In function getOptionArray() if I pass the static value in array it show the value in grid form.

In the above code I am getting below error:-

Uncaught Error: Using $this when not in object context in <magento  installation path>/app/code/Complay/Module/Model/Probore.php:37

this is my helper code:-

namespace Company\Module\Helper;

class Data extends \Magento\Framework\App\Helper\AbstractHelper
{

    protected $eavConfig;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_urlBuilder;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_customerSession;

    /**
     * @var \Magento\Framework\App\Config\ScopeConfigInterface
     */
    protected $_productFactory;

    /**
     * Initialize
     *
     * @param \Magento\Framework\App\Helper\Context $context
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param \Magento\Customer\Model\Session $customerSession
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        \Magento\Customer\Model\Session $customerSession,
        \Magento\Eav\Model\Config $eavConfig
    ) {
        $this->_productFactory = $productFactory;
        $this->_urlBuilder = $context->getUrlBuilder();
        $this->_customerSession = $customerSession;
        $this->eavConfig = $eavConfig;
        parent::__construct($context);
    }

    /**
     *  Get form action url
     */
    public function getFormAction() {
        return $this->_urlBuilder->getUrl('callforprice/callprice/save');
    }

    /**
     *  Get configuration settings value
     */
    public function getConfigValue($value = '') {
        return $this->scopeConfig
                ->getValue(
                        $value,
                        \Magento\Store\Model\ScopeInterface::SCOPE_STORE
                        );
    }

    /**
     *  Get product sku
     */
    public function getProductSku($prodId) {
        $product = $this->_productFactory->create();
        $product->load($prodId);
        return $product->getSku();
    }

    /**
     *  Get product url
     */
    public function getProductUrl($prodId) {
        $product = $this->_productFactory->create();
        $product->load($prodId);
        return $product->getUrlKey();
    }

    /**
     *  Get customer name
     */
    public function getUserName() {
        if (!$this->_customerSession->isLoggedIn()) {
            return '';
        }
        $customer = $this->_customerSession->getCustomerDataObject();
        return $customer->getFirstName() . ' ' . $customer->getLastName();
    }

    /**
     *  Get customer email
     */
    public function getUserEmail() {
        if (!$this->_customerSession->isLoggedIn()) {
            return '';
        }
        /**
         * @var CustomerInterface $customer
         */
        $customer = $this->_customerSession->getCustomerDataObject();
        return $customer->getEmail();
    }

    public function getStoreBaseUrl(){
        return $this->_storeManager->getStore()
                ->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
    }

    public function getAttributeLabel()
    {
       $attribute = $this->eavConfig->getAttribute('catalog_product', 'boretype');
       $options = $attribute->getSource()->getAllOptions();
       return $options;
    }
}

boretype is a dropdown type product attribute.

Best Answer

Create a helper function for this

you can add to the constructor of your class an instance of \Magento\Eav\Model\Config like this:

protected $eavConfig;
public function __construct(
    ...
    \Magento\Eav\Model\Config $eavConfig,
    ...
){
    ...
    $this->eavConfig = $eavConfig;
    ...
}

then you can use that in your class

public function <func_name>()
{
   $attribute = $this->eavConfig->getAttribute('catalog_product', 'attribute_code_here');
   $options = $attribute->getSource()->getAllOptions();
   return $options;
}

Then in your model file add to the constructor of your helper class an instance like this:

public function __construct(\Namespace\Module\Helper\Helper_name $helper)
{
    $this->helper = $helper;
}

then replace your getOptions function with this :

public function getOptions()
{
    $data = $this->helper-><func_name>();
    $res = [];
    foreach ($data as $index => $value) {
       $res[] = ['value' => $value['value'], 'label' => $value['label']];
    }
    return $res;
}
Related Topic