HowTo: Use the InsertListing Ui Component in Magento 2
On this page
Every now and then you need to embed a grid inside a form, think of the “add products to a category” screen, where a
listing lets you tick the records you want and the selection is stored with the parent entity. The component that makes
this possible is insertListing, and it is one of the most useful, and most confusing, Ui Components in Magento.
Add the insertListing to your form
Inside a fieldset of your form, you declare an insertListing field. It references an existing listing by name and
tells the form how to exchange data with it.
<?xml version="1.0"?>
<!-- app/code/Vendor/Module/view/adminhtml/ui_component/vendor_entity_form.xml -->
<form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Ui:etc/ui_configuration.xsd">
<fieldset name="items">
<settings>
<label translate="true">Selected items</label>
</settings>
<insertListing name="vendor_entity_items_listing">
<settings>
<autoRender>true</autoRender>
<dataScope>vendor_entity_items_listing</dataScope>
<externalProvider>vendor_entity_items_listing.vendor_entity_items_listing_data_source</externalProvider>
<selectionsProvider>vendor_entity_items_listing.vendor_entity_items_listing.item_columns.ids</selectionsProvider>
<ns>vendor_entity_items_listing</ns>
<exportField>selected_items</exportField>
<imports>
<link name="storeId">${ $.provider }:data.store_id</link>
</imports>
</settings>
</insertListing>
</fieldset>
</form>The two settings that trip people up are:
selectionsProvider— the path to the checkbox column of the listing. This is what tells the form which rows are ticked.exportField— the field of the form where the selected ids end up, so they are submitted together with the rest of the form on save.
The listing needs a checkbox column
For the selection to work, the referenced listing must have a selectionsColumn:
<columns name="item_columns">
<selectionsColumn name="ids">
<settings>
<indexField>entity_id</indexField>
</settings>
</selectionsColumn>
<!-- your other columns -->
</columns>On save, read selected_items from the form data and persist the relationship in your own table. Deploy the admin
static content, flush the cache, and you get a grid embedded right inside the form with its selection wired to the
parent record.
Hope this helps.
If you have any question or know a better way to achieve this, feel free to share in the comments below.