0

I am showing multiselect dropdown in user form in admin panel(System->All user->Add User) I have created a plugin for creating field in that form. Here is the code, I am using:

public function aroundGetFormHtml(
    \Magento\User\Block\User\Edit\Tab\Main $subject,
    \Closure $proceed
) {
    $_objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $registry = $_objectManager->get('Magento\Framework\Registry');
    $model = $registry->registry('permissions_user');
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $form = $subject->getForm();
    if (is_object($form)) {
            $fieldset = $form->addFieldset('user_attribute_fieldset', ['legend' => __('User Category')]);
            // Gather our existing categories
            $currentCategories = $this->_getExistingCategories($model);
            $fieldset->addField(
                'user_fields',
                'multiselect',
                [
                    'name' => 'user_fields',
                    'label' => __('user fields'),
                    'id' => 'user_fields',
                    'title' => __('user fields'),
                    'value' => $currentCategories,//for selected value
                    'values' => $objectManager->create('{namespace}\{module}\Helper\Data')->getOptions()//for all options
                ]
            );
             $subject->setForm($form);

    }
    return $proceed();
}

Now I want to create this as a Multi Select UI Field, shown below: enter image description here

how I can implement ui select component in existing magento forms not made with ui components?

Thanks in advance:)

  • I ain't sure but you can't add ui_component in form developed using PHP, You need to create whole form with ui_component than you can add Multiselect as you mentioned in question. – Vivek May 30 '18 at 11:14
  • But its magento's default form, how can I recreate the whole form through UI component? – user00247 May 30 '18 at 11:35
  • Hello. Did you solved this issue? I face same issue. Can you please post answer if you sovled already? – Dharmik Ponda Apr 29 at 12:36
  • @Denish please check my answer, hope it helps. – user00247 Apr 30 at 6:22
0

Firstly add a field in your ui-form:

<field name="custom" component="Namespce_Modulename/js/select-category" sortOrder="20" formElement="select">
<argument name="data" xsi:type="array">
 <item name="config" xsi:type="array">
    <item name="filterOptions" xsi:type="boolean">true</item>
     //to add filter in select-ui
    <item name="multiple" xsi:type="boolean">false</item>//select multiple or not
    <item name="showCheckbox" xsi:type="boolean">true</item>//to show checkboxes
    <item name="disableLabel" xsi:type="boolean">true</item>
</item>
</argument>
<settings>
<required>true</required>
<validation>
    <rule name="required-entry" xsi:type="boolean">true</rule>
</validation>
<elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
<label translate="true">Select Category</label>//label to Field
<dataScope>data.custom</dataScope>//To map
<componentType>field</componentType>
<listens>
    <link name="${ $.namespace }.${ $.namespace }:responseData">setParsed</link>
</listens>
</settings>
<formElements>
<select>
    <settings>
        <options class="Namespace\ModuleName\Ui\Component\Form\Category\Options"/>
    </settings>
</select>
 </formElements>

Now create Js file to map the field's value:

Namespace_Modulename/view/adminhtml/web/js/select-category.js

define([
'Magento_Ui/js/form/element/ui-select'
], function (Select) {
'use strict';
return Select.extend({
/**
 * Parse data and set it to options.
 *
 * @param {Object} data - Response data object.
 * @returns {Object}
 */
setParsed: function (data) {
    var option = this.parseData(data);
    if (data.error) {
        return this;
    }
    this.options([]);
    this.setOption(option);
    this.set('newOption', option);
},
/**
 * Normalize option object.
 *
 * @param {Object} data - Option object.
 * @returns {Object}
 */
parseData: function (data) {
    return {
        value: data.category.entity_id,
        label: data.category.name
    };
}
});
});

Create a file to get options to display:

Namespace\ModuleName\Ui\Component\Form\Category\Options.php

<?php
namespace Namespace\ModuleName\Ui\Component\Form\Category;

use Magento\Framework\Data\OptionSourceInterface;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory as         CategoryCollectionFactory;
use Magento\Framework\App\RequestInterface;

/**
 * Options tree for "Categories" field
*/
class Options implements OptionSourceInterface
{

protected $categoryCollectionFactory;

 /**
  * @var RequestInterface
 */
 protected $request;

 /**
 * @var array
 */
 protected $categoryTree;

 /**
  * @param CategoryCollectionFactory $categoryCollectionFactory
  * @param RequestInterface $request
  */
public function __construct(
CategoryCollectionFactory $categoryCollectionFactory,
RequestInterface $request
) {
$this->categoryCollectionFactory = $categoryCollectionFactory;
$this->request = $request;
}

/**
* {@inheritdoc}
*/
public function toOptionArray()
{
return $this->getCategoryTree();
}


/**
* Retrieve categories tree
*
* @return array
*/
protected function getCategoryTree()
{
if ($this->categoryTree === null) {
    $collection = $this->categoryCollectionFactory->create();

    $collection->addAttributeToSelect('name');

    foreach ($collection as $category) {
        $categoryId = $category->getEntityId();
        if (!isset($categoryById[$categoryId])) {
            $categoryById[$categoryId] = [
                'value' => $categoryId
            ];
        }
        $categoryById[$categoryId]['label'] = $category->getName();
    }
    $this->categoryTree = $categoryById;
   }
   return $this->categoryTree;
   }
 }

Hope it helps!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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