0

How to set product's attribute dropdown option programmatically?

3
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.