In this recipe, a lightning-record-picker
is used in combination with a lightning-pill-container
to allow fur multiple record selection.
In fact, lightning-record-picker
only supports a single record selection. So, this recipe shows how to circumvent this limitation allowing several records to be selected by the user.
<aside>
đź“‚ You can find the LWC in this folder: force-app\\main\\default\\lwc\\recordPickerMultiValue
.
</aside>
There are 2 components in the template: the records’ selected UI component (a lightning-pill-container
) and the find and record selector (lightning-record-picker
).
...
<div>
<lightning-record-picker
lwc:ref="recordPicker"
label="Contacts"
placeholder="Search Contacts..."
object-api-name="Contact"
filter={recordPickerFilter}
onchange={handleRecordPickerChange}
></lightning-record-picker>
</div>
<lightning-pill-container
items={pillItems}
onitemremove={handlePillRemove}
></lightning-pill-container>
...
The record-picker used is much simpler than the one used in the previous recipe, as it used the filter
attribute to filter out those already selected contacts.
If you want to have a better user experience please add the following attribute in the toContactPill
function:
href: '/' + record.id.toString(), // Allows to navigate to the contact with a click
The Javascript starts with 2 functions that allow transformation between data and UI elements:
toContactPill
converts a record, in this case a Contact record, to the data pill format (for more information about the pill-container, review the official documentation: https://developer.salesforce.com/docs/component-library/bundle/lightning-pill-container/documentation)toRecordPickerFilter
: converts the already selected Contact IDs to the record-picker filter format, so these records do not appear if they match the user search again.There are also 3 getter functions that are used to retrieve the value for the following properties:
pillItems
: retrieves the selected contacts stored in the selectedRecords
variable using the toContactPill
function.recordPickerFilter
: retrieves the selected contacts stored in the selectedRecords
variable using the toRecordPickerFilter
function.The contact selection management is done through the handleRecordPickerChange
handler:
handleRecordPickerChange(event) {
this.selectedRecordId = event.detail.recordId;
}
As the handler updates the selectedRecordId
reactive property the GraphQL query is executed: