How to set product's attribute dropdown option programmatically?
-
which area you are looking for to display? either frontstore or adminhtml?– BojjaiahCommented Jun 15, 2017 at 10:44
-
Do you mean something like this? magento.stackexchange.com/questions/192160/…– Dominic PixieCommented 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.– Shawn AbramsonCommented Jan 29, 2021 at 4:27
Add a comment
|
1 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.