1

Is it possible to add a select input to a product where the options are dynamic?

I've specified the path like so:

$eavSetup->addAttribute(
        \Magento\Catalog\Model\Product::ENTITY,
        'manufacturer',
        [
            'type' => 'int',
            'backend' => '',
            'frontend' => '',
            'label' => 'Manufacturer',
            'input' => 'select',
            'class' => '',
            'source' => 'Amrita\Catalog\Model\Config\Source\Options',
            'global' => Attribute::SCOPE_GLOBAL,
            'visible' => true,
            'required' => true,
            'user_defined' => false,
            'default' => 0,
            'searchable' => false,
            'filterable' => false,
            'comparable' => false,
            'visible_on_front' => false,
            'used_in_product_listing' => true,
            'unique' => false,
            'apply_to' => ''
        ]
    );

In Options.php i've injected the manufacturerCollectionFactory like so

 public function __construct(OptionFactory $optionFactory, CollectionFactory $manufacturerCollectionFactory)
    {
        $this->optionFactory = $optionFactory;
        $this->manufacturerCollectionFactory = $manufacturerCollectionFactory;
        //you can use this if you want to prepare options dynamically

    }

I've then tried to add the options in a loop after retrieving the manufacturer collection. I need to set the value and the label of the option by getting the id and title of the manufacturer object, but i'm not sure how to do this using OptionFactory. setLabel() setValue() doesn't work, is there anything equivalent?

    public function getAllOptions()
    {
        $manufacturers = $this->manufacturerCollectionFactory->create();
        foreach ($manufacturers as $manufacturer) {
            $option = $this->optionFactory->create();     
//            $option->setLabel();
//            $option->setValue();
//            array_push($this->_options, $option);
        }

        return $this->_options;
    }
0

1 Answer 1

2

I solved this issue as follows,

public function getAllOptions()
    {
        $manufacturers = $this->manufacturerCollectionFactory->create();
        foreach ($manufacturers as $manufacturer) {
            $this->_options[] = [
                    'label' => __($manufacturer['title']),
                    'value' => $manufacturer['id'],
                ];
        }

        return $this->_options;
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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