0

How to set product's attribute dropdown option programmatically?

3
  • which area you are looking for to display? either frontstore or adminhtml?
    – Bojjaiah
    Commented Jun 15, 2017 at 10:44
  • Do you mean something like this? magento.stackexchange.com/questions/192160/… Commented May 15, 2019 at 18:38
  • Please be more specific about what you are trying to accomplish. Your question is too general for anybody to answer. Commented Jan 29, 2021 at 4:27

1 Answer 1

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 and acknowledge you have read our privacy policy.

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