I need to create an extension that will store options of multiselect customer attribute in the database, and I can add through database new options. There are many answers of how to create multiselect customer attribute, and all of them show how to store options in the file, but none how to store in the database. I tried to find similar functionality in magento2, but customer doesn't have multiselect attribute.
InstallData.php:
namespace Vendor\Extension\Setup;
use Magento\Eav\Model\Config;
use Magento\Eav\Setup\EavSetup;
use Magento\Eav\Setup\EavSetupFactory;
use Magento\Framework\Setup\InstallDataInterface;
use Magento\Framework\Setup\ModuleContextInterface;
use Magento\Framework\Setup\ModuleDataSetupInterface;
class InstallData implements InstallDataInterface
{
private $eavSetupFactory;
public function __construct(
EavSetupFactory $eavSetupFactory,
Config $eavConfig
) {
$this->eavSetupFactory = $eavSetupFactory;
$this->eavConfig = $eavConfig;
}
public function install(
ModuleDataSetupInterface $setup,
ModuleContextInterface $context
) {
$eavSetup = $this->eavSetupFactory->create(["setup" => $setup]);
//magento 2 create customer dropdown attribute programmatically
$eavSetup->addAttribute(
\Magento\Customer\Model\Customer::ENTITY,
"custom_multiselect",
[
"label" => "Customer multiselect segment",
"system" => 0,
"position" => 800,
"sort_order" => 800,
"visible" => true,
"note" => "",
"type" => "text",
"input" => "multiselect",
"source" => "Vendor\Extension\Model\Source\Custommultiselect",
]
);
$this->getEavConfig()
->getAttribute("customer", "custom_multiselect")
->setData("is_user_defined", 1)
->setData("is_required", 0)
->setData("default_value", 22)
->setData("used_in_forms", [
"adminhtml_customer",
"checkout_register",
"customer_account_create",
"customer_account_edit",
"adminhtml_checkout",
])
->save();
}
public function getEavConfig()
{
return $this->eavConfig;
}
}
Custommultiselect.php
namespace Vendor\Extension\Model\Source;
class Custommultiselect extends
\Magento\Eav\Model\Entity\Attribute\Source\AbstractSource
{
public function getAllOptions()
{
if ($this->_options === null) {
$this->_options = [
["value" => "1", "label" => __("default")],
["value" => "2", "label" => __("Test")],
["value" => "3", "label" => __("Test2")]
];
}
return $this->_options;
}
public function getOptionText($value)
{
foreach ($this->getAllOptions() as $option) {
if ($option["value"] == $value) {
return $option["label"];
}
}
return false;
}
}
So basically I need to store: default, Test, Test2 in the database, for example here eav_attribute_option
Any help would be appreciated.