Question

I'm trying to build a CRUD module for Magento 2.
In this module, one of my entities has a "many to many" relation with the products.
For this, I need to add a section in my add/edit form where I can select the products.
I want to do this using form ui components, not with tabs.
I thought I could replicate the way the related products are done in the product add/edit form.
But there is a problem. I don't understand how is that added to the product form.
From what I saw, the product form uses ui components.
So how is the related products section added to the product edit screen?

Was it helpful?

Solution

Based on the guidance from @DavidVerholen I managed to find out how the related products are added to the product add/edit page.
The ui component must have a data provider class associated to it.
For products this data provider is Magento\Catalog\Ui\DataProvider\Product\Form\ProductDataProvider.
This is assigned to the ui component in product_form.xml

<dataSource name="product_form_data_source">
    <argument name="dataProvider" xsi:type="configurableObject">
        <argument name="class" xsi:type="string">Magento\Catalog\Ui\DataProvider\Product\Form\ProductDataProvider</argument>
        ....
    </argument>
    ....
</dataSource> 

But this data provider supports modifiers.
each modifier can do 2 things.

  • change the configuration of the ui component
  • change the data attached to the component.

The product form component has a lot of modifiers attached to it in adminhtml/di.xml.
One of these modifiers is the Related modifier

<virtualType name="Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool" type="Magento\Ui\DataProvider\Modifier\Pool">
    <arguments>
        <argument name="modifiers" xsi:type="array">
            ....
            <item name="related" xsi:type="array">
                <item name="class" xsi:type="string">Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related</item>
                <item name="sortOrder" xsi:type="number">110</item>
            </item>
            ...
        </argument>
    </arguments>
</virtualType>
<type name="Magento\Catalog\Ui\DataProvider\Product\Form\ProductDataProvider">
    <arguments>
        <argument name="pool" xsi:type="object">Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Pool</argument>
    </arguments>
</type>

the modifier for related is an instance of Magento\Catalog\Ui\DataProvider\Product\Form\Modifier\Related.
There are 2 methods in this modifier that are important.

  • modifyMeta: this one modifies the ui component structure by adding an other fieldset with related products, up-sells and cross-sells.
  • modifyData: retrieves the related products (and other relations) from the db and attaches the values to the data that should appear in the form.

I guess I could try the same approach on my ui component.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top