Skip to content

Preselect saved categories in Magento UI component

In Manage Categories, I want to add a field called ‘category_selector’ to select categories
and save them to my table child_categories with a column called categories.
the code below, displays the category tree but I need it to preselect saved categories from my table.

<?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="content" >
        <field name="category_selector" component="X_Y/js/form/element/category-selector" formElement="select">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="filterOptions" xsi:type="boolean">true</item>
                    <item name="multiple" xsi:type="boolean">true</item>
                    <item name="showCheckbox" xsi:type="boolean">true</item>
                    <item name="disableLabel" xsi:type="boolean">true</item>
                    <item name="sortOrder" xsi:type="number">300</item>
                </item>
            </argument>
            <settings>
                <required>false</required>
                <validation>
                    <rule name="required-entry" xsi:type="boolean">false</rule>
                </validation>
                <elementTmpl>ui/grid/filters/elements/ui-select</elementTmpl>
                <label translate="true">Child Categories</label>
                <dataScope>categories</dataScope>
                <componentType>field</componentType>
                <listens>
                    <link name="X_Y/js/form/element/category-selector:responseData">setParsed</link>
                </listens>
            </settings>
            <formElements>
                <select>
                    <settings>
                        <options class="MagentoCatalogUiComponentProductFormCategoriesOptions"/>
                    </settings>
                </select>
            </formElements>
        </field>
    </fieldset>
</form>