0

How to set product's attribute dropdown option programmatically?

3

2 Answers 2

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.

0

You can use this code to add product dropdown attribute:

public function createOrGetId($attributeCode, $label)
{
    if (strlen($label) < 1) {
        throw new \Magento\Framework\Exception\LocalizedException(
            __('Label for %1 must not be empty.', $attributeCode)
        );
    }

    // Does it already exist?
    $optionId = $this->getOptionId($attributeCode, $label);

    if (!$optionId) {
        // If no, add it.

        /** @var \Magento\Eav\Model\Entity\Attribute\OptionLabel $optionLabel */
        $optionLabel = $this->optionLabelFactory->create();
        $optionLabel->setStoreId(0);
        $optionLabel->setLabel($label);

        $option = $this->optionFactory->create();
        $option->setLabel($label);
        $option->setStoreLabels([$optionLabel]);
        $option->setSortOrder(0);
        $option->setIsDefault(false);

        $this->attributeOptionManagement->add(
            \Magento\Catalog\Model\Product::ENTITY,
            $this->getAttribute($attributeCode)->getAttributeId(),
            $option
        );

        // Get the inserted ID. Should be returned from the installer, but it isn't.
        $optionId = $this->getOptionId($attributeCode, $label, true);
    }

    return $optionId;
}
/**
 * Get option Id
 *
 * @param string $attributeCode
 * @param string $label
 * @param bool $force
 * @return bool|mixed
 * @throws \Magento\Framework\Exception\NoSuchEntityException
 */
public function getOptionId($attributeCode, $label, $force = false)
{
    /** @var \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attribute */
    $attribute = $this->getAttribute($attributeCode);

    // Build option array if necessary
    if ($force === true || !isset($this->attributeValues[ $attribute->getAttributeId() ])) {
        $this->attributeValues[ $attribute->getAttributeId() ] = [];

        // We have to generate a new sourceModel instance each time through to prevent it from
        // referencing its _options cache. No other way to get it to pick up newly-added values.

        /** @var \Magento\Eav\Model\Entity\Attribute\Source\Table $sourceModel */
        $sourceModel = $this->tableFactory->create();
        $sourceModel->setAttribute($attribute);

        foreach ($sourceModel->getAllOptions() as $option) {
            $this->attributeValues[ $attribute->getAttributeId() ][ $option['label'] ] = $option['value'];
        }
    }

    // Return option ID if exists
    if (isset($this->attributeValues[ $attribute->getAttributeId() ][ $label ])) {
        return $this->attributeValues[ $attribute->getAttributeId() ][ $label ];
    }

    // Return false if does not exist
    return false;
}

/**
 * Get attribute
 *
 * @param string $attributeCode
 * @return \Magento\Catalog\Api\Data\ProductAttributeInterface
 * @throws \Magento\Framework\Exception\NoSuchEntityException
 */
public function getAttribute($attributeCode)
{
    return $this->attributeRepository->get($attributeCode);
}

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.