In this recipe, a lightning-record-picker
is used in combination with a lightning-combobox
to simulate that the user can select values from several objects.
In fact, lightning-record-picker
only supports a single object, called the target. So, this recipe shows how to circumvent this limitation with 2 components and additional code.
The target object is selected in the combobox and then, the records retrieved using the record-picker belong to this object.
If a record is selected, the combobox component is hidden, and the selected record is the only element shown.
<aside>
📂 You can find the LWC in this folder: force-app\\main\\default\\lwc\\recordPickerDynamicTarget
.
</aside>
There are 2 components in the template: the object selector (combobox) and the record selector (picker).
The lightning-combobox
is shown only if a record has not been yet selected. When the user changes from one object to another, for example from Account to Contact, the picker is cleared from any text introduced previously by the user.
The lightning-record-picker
uses the property selectedTarget
to target the right object selected by the user (so far, in the previous recipes, this value was hard-coded).
...
<div class="slds-form-element__control slds-combobox-group">
<template lwc:if={showTargetSelector}>
<!-- Target selector -->
<lightning-combobox
data-id="targetSelector"
label="Select a target sObject"
variant="label-hidden"
options={targetObjects}
value={selectedTarget}
onchange={handleTargetSelection}
class="slds-combobox_object-switcher slds-combobox-addon_start"
>
</lightning-combobox>
</template>
<lightning-record-picker
lwc:ref="recordPicker"
object-api-name={selectedTarget}
placeholder="Search..."
label="Select a record"
variant="label-hidden"
display-info={displayInfo}
matching-info={matchingInfo}
onchange={handleRecordSelect}
class="slds-size_full slds-combobox-addon_end"
>
</lightning-record-picker>
</div>
...
To manage the several possible targets, 2 arrays are created. Corresponding getters functions for displayInfo
and the matchingInfo
provide the right values.
...
displayInfos = {
Account: {
additionalFields: ['Type']
},
Contact: {
additionalFields: ['Phone']
}
};
matchingInfos = {
Account: {
additionalFields: [{ fieldPath: 'Type' }]
},
Contact: {
additionalFields: [{ fieldPath: 'Phone' }]
}
};
get displayInfo() {
return this.displayInfos[this.selectedTarget];
}
get matchingInfo() {
return this.matchingInfos[this.selectedTarget];
}
...
Did you find an issue/mistake? You don’t like something? Do you have external content that I should link to improve the learning process? Did you find it helpful? Any of those are super valuable to me. So, please write me at [email protected], and promise to answer.
<aside> ↗️ Jump to the main page: The LWC Recipes Cookbook
</aside>