Magento – Magento 2.1 – Add category selector field in backend custom model form

adminformbackendformsmagento2

I'm creating my custom model form on a backend module. I need to allow the admins to select one category for my model, so I wanted to use the Magento standard category selector, like this example :

Magento 2 standard category selector

How can I do ?

FYI, I'm using form fieldset to add fields, like this example:

$fieldset->addField(
        'field_name',
        'text',
        [
            'name' => 'field_name',
            'label' => __('Field Label'),
            'title' => __('Field Title'),
            'required' => false
        ]
    );

There are similar questions, but none of them has a valid answer for the moment.

Best Answer

Well, I have achieved this through the UI Form. Actually I have not got the solution to add a category tree in block form. Then I used the UI form and it's worked.

Add this code in your custom UI form.

<field name="category_id">
            <argument name="data" xsi:type="array">
                <item name="options" xsi:type="object">Magento\Catalog\Ui\Component\Product\Form\Categories\Options</item>
                <item name="config" xsi:type="array">
                    <item name="label" xsi:type="string" translate="true">Select Category</item>
                    <item name="componentType" xsi:type="string">field</item>
                    <item name="formElement" xsi:type="string">select</item>
                    <item name="component" xsi:type="string">Magento_Catalog/js/components/new-category</item>
                    <item name="elementTmpl" xsi:type="string">ui/grid/filters/elements/ui-select</item>
                    <item name="dataScope" xsi:type="string">category_id</item>
                    <item name="filterOptions" xsi:type="boolean">true</item>
                    <item name="showCheckbox" xsi:type="boolean">false</item>
                    <item name="disableLabel" xsi:type="boolean">true</item>
                    <item name="multiple" xsi:type="boolean">false</item>
                    <item name="levelsVisibility" xsi:type="number">1</item>
                    <item name="sortOrder" xsi:type="number">20</item>
                    <item name="required" xsi:type="boolean">true</item>
                    <item name="validation" xsi:type="array">
                        <item name="required-entry" xsi:type="boolean">true</item>
                    </item>

                    <item name="additionalClasses" xsi:type="string">category_id</item>



                    <item name="listens" xsi:type="array">
                        <item name="${ $.namespace }.${ $.namespace }:responseData" xsi:type="string">setParsed</item>
                    </item>
                </item>
            </argument>
        </field>
Related Topic