Custom Fields Multiselect Product Add Edit Pages Magento 2

This is a quite important demand when you want to use extra information on your pages which the default system does not include.

You can add custom fields with the help of UI Component.

Follow the below steps to create the module ‘PHPCodez_Customfield’

1) Declare a module.

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
<module name="PHPCodez_Customfield" setup_version="0.0.1" />
</config>

2) Register a module.

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'PHPCodez_Customfield',
__DIR__
);

3) Generate UI Component

<?xml version="1.0" encoding="UTF-8"?>
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd"> 
<fieldset name="product_access">
<argument name="data" xsi:type="array"> 
<item name="config" xsi:type="array">
<item name="label" xsi:type="string" translate="true">Product Access</item>
<item name="dataScope" xsi:type="string"/>
<item name="sortOrder" xsi:type="number">0</item>
<item name="collapsible" xsi:type="boolean">true</item>
<item name="opened" xsi:type="boolean">false</item>
</item>
</argument>
<field name="customer_group">
<argument name="data" xsi:type="array">
<item name="options" xsi:type="object">PHPCodez\Customfield\Model\Config\Source\Group\Multiselect</item>
<item name="config" xsi:type="array">
<item name="dataType" xsi:type="string">text</item>
<item name="label" translate="true" xsi:type="string">Hide Products For</item>
<item name="formElement" xsi:type="string">multiselect</item>
</item>
</argument>
</field> 
</fieldset>
</form>

4) Create source model for multiselect field.

<?php
namespace PHPCodez\Customfield\Model\Config\Source\Group;
use \Magento\Customer\Model\ResourceModel\Group\Collection;

class Multiselect extends \Magento\Eav\Model\Entity\Attribute\Source\AbstractSource implements \Magento\Framework\Option\ArrayInterface {

protected $_customerGroup;

protected $_options;

public function __construct( Collection $customerGroup ) {
$this->_customerGroup = $customerGroup; 
}

public function toOptionArray() {
if (!$this->_options) {
$this->_options = $this->_customerGroup->toOptionArray();
}
return $this->_options;
}

public function getAllOptions() {

if (!$this->_options) {
$this->_options = $this->_customerGroup->toOptionArray();
}
return $this->_options;
}
}

5) Issue the following commands.

$ php bin/magento indexer:reindex
$ php bin/magento setup:upgrade
$ php bin/magento setup:di:compile
$ php bin/magento setup:static-content:deploy -f
$ php bin/magento cache:flush
Share

Leave a Reply

Your email address will not be published. Required fields are marked *