Magento – Magento 2: Set attribute dropdown option programmatically

magento-2.1magento2product-attribute

How to set product's attribute dropdown option programmatically?

Best Answer

you can try below code

<?php

namespace ABCCompany\Theme\Block\Adminhtml\Form\Field\Product;

class ProductAttributes extends \Magento\Framework\View\Element\Html\Select
{
    /**
     * @var \Magento\Catalog\Model\ProductFactory
     */
    protected $product_Factory;

    protected $attributesArrays;

    /**
     * @param \Magento\Framework\View\Element\Context $context
     * @param \Magento\Catalog\Model\ProductFactory $productFactory
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Context $context,
        \Magento\Catalog\Model\ProductFactory $productFactory,
        array $data = []
    ) {
        parent::__construct($context, $data);
        $this->product_Factory = $productFactory;
    }

    /**
     * Retrieve all Product Attributes
     *
     * @return mixed
     */
    protected function _getProductAttributes()
    {

        $attributes = $this->product_Factory->create()->getAttributes();

        foreach($attributes as $cal => $val){
            $this->attributesArrays[$cal] = $cal;
        }

        return $this->attributesArrays;
    }

    /**
     * @param string $value
     * @return $this
     */
    public function setInputName($value)
    {
        return $this->setName($value);
    }

    /**
     * Render block HTML
     *
     * @return string
     */
    public function _toHtml()
    {
        if (!$this->getOptions()) {

            if (true) {
                $this->addOption('select',__('--Select--'));
            }

            foreach ($this->_getProductAttributes() as $key => $val) {
                $this->addOption($key, addslashes($val));
            }
        }
        return parent::_toHtml();
    }

}

feel free to ask if any info.