How to set value for radio button in EAV attribute of product type?
-
20-02-2021 - |
سؤال
We can add simple boolean Radio buttons as EAV attribute in install schema by this code:
"type" => "int",
"backend" => "",
"label" => "Test",
"input" => "boolean",
"source" => 'Magento\Eav\Model\Entity\Attribute\Source\Boolean',
"visible" => true,
"required" => true,
"default" => "",
"frontend" => "",
"unique" => false,
"note" => ""
But if we want to add more than two options or other than 'Yes'/'No' Type then how to achieve this. I guess this could be in source attribute but have no idea how return the options in custom file i.e. to which file extends or implements and which function need to be used. I am unable to find the answer anywhere else. Thanks
المحلول
Create Attribute
$eavSetup->updateAttribute(
\Magento\Catalog\Model\Product::ENTITY, 'custom_attribute_name',
[
'type' => 'int',
'backend' => 'Magento\Eav\Model\Entity\Attribute\Backend\ArrayBackend',
'frontend' => '',
'label' => 'Custom Attribute Name',
'input' => 'boolean',
'group' => 'General',
'class' => 'custom_attribute_name',
'source' => 'Custom\Product\Model\YesNo',
'global' => ScopedAttributeInterface::SCOPE_GLOBAL,
'visible' => true,
'required' => true,
'user_defined' => false,
'default' => '1',
'searchable' => false,
'filterable' => false,
'comparable' => false,
'visible_on_front' => false,
'used_in_product_listing' => true,
'unique' => false
]
);
Create File Custom\Product\Model\YesNo For Options
<?php
namespace Custom\Product\Model;
class YesNo extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
protected $_options;
/**
* getAllOptions
*
* @return array
*/
public function toOptionArray()
{
return array(
array('value' => '1', 'label' => __('Yes')),
array('value' => '0', 'label' => __('No'))
..................
);
}
public function getAllOptions()
{
return $this->toOptionArray();
}
}
You Can Add Options In toOptionArray() Function
نصائح أخرى
You can set custom source like:
Vendor\Module\Model\Source\RadioOptions
Now create a Model with name "RadioOptions" under
Vendor\Module\Model\Source
namespace Vendor\Module\Model\Source;
class RadioOptions extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
protected $_options = array();
/**
* Abstract method of source class
* @return type
*/
public function getAllOptions()
{
$this->_options = array(
array(
'label' => __('Male'),
'value' => 'male',
),
array(
'label' => __('Female'),
'value' => 'female',
)
);
return $this->_options;
}
/**
* Abstract method of source class that returns data
* @param $value
* @return boolean
*/
public function getOptionText($value)
{
$options = $this->getAllOptions(false);
foreach ($options as $item) {
if ($item['value'] == $value) {
return $item['label'];
}
}
return false;
}
}
This may help you.
لا تنتمي إلى magento.stackexchange