Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Salesforce Lookup Component built with Lightning Web Components.

License

NotificationsYou must be signed in to change notification settings

pozil/sfdc-ui-lookup-lwc

Repository files navigation

Now compatible withSLDS 2!

Github Workflowcodecova11y friendly

Important

The Winter '24 release introduces a new Lightning base component that is similar to this lookup component:lightning-record-picker (release announcement).Here is a table to help you understand the key differences (non-exhaustive) between the two components:

This Lookup componentlightning-record-picker
SupportCustom component built as OSS. No official support.Base Lightning component with official Salesforce support.
Mobile SupportNone.Built-in.
Data SourceYou control the implementation (GraphQL or Apex) and you can work with any kind of data. It can list records or data that lives outside of the Platform.You don't control the data source implementation (less code required). The component only selects Salesforce records with some filtering capabilities.
CacheYou have to take care of caching as part of the implementation and you can use the Lightning Data Service.Built-in with Lightning Data Service caching and partial support for offline mode.
PermissionsAutomatically enforced if using GraphQL. Can be enforced or bypassed if using Apex (use this with caution).Automatically enforced.
Multi ObjectBuilt-in. You can select records from multiple objects/sources.Not supported but on the roadmap*.
Multi SelectionBuilt-in.Not supported but on the roadmap*.
Default ResultsCustomizable with the data of your choice: recently viewed records or other.Not customizable but recently viewed records are on the roadmap*.
Custom ActionsAbility to create new records from the lookup.Not supported but on the roadmap*.

* Forward-Looking Statements. No estimated date of delivery or guarantees.


Lookup animation

Lookup with dropdown open

  1. About
  2. Installation
  3. Documentation
    1. Getting started
    2. Handling selection changes (optional)
    3. Providing default search results (optional)
    4. Saving form state when creating new records (optional)
    5. Passing custom data to JavaScript and Apex (optional)
  4. Reference
  5. Special use cases
    1. Working with picklists values

About

This is a generic & customizable lookup component built using SalesforceLightning Web Components andSLDS style.
It does not rely on third party libraries and you have full control over its datasource.

Features

The lookup component provides the following features:

  • customizable data source that can return mixed sObject types
  • single or multiple selection mode
  • client-side caching & request throttling
  • great test coverage
  • full accessibility (a11y) compliance
  • keyboard navigation
  • search term highlighting
  • ability to create new records

Multiple or single entry lookup

Installation

The default installation installs the lookup component and a sample application available under this URL (replace the domain):
https://YOUR_DOMAIN.lightning.force.com/c/SampleLookupApp.app

If you wish to install the project without the sample application, editsfdx-project.json and remove thesrc-sample path.

Install the sample app by running this script:

MacOS or Linux

./install-dev.sh

Windows

install-dev.bat

Documentation

Getting Started

Follow these steps to use the lookup component:

  1. Write the search endpoint

    Implement an Apex@AuraEnabled(cacheable=true scope='global') method (SampleLookupController.search in our samples) that returns the search results as aList<LookupSearchResult>.The method name can be different, but it needs to match this signature:

    @AuraEnabled(cacheable=truescope='global')publicstaticList<LookupSearchResult>search(StringsearchTerm,List<String>selectedIds) {}
  2. Import a reference to the search endpoint

    Import a reference to thesearch Apex method in the lookup parent component's JS:

    importapexSearchfrom'@salesforce/apex/SampleLookupController.search';
  3. Handle the search event and pass search results to the lookup

    The lookup component exposes asearch event that is fired when a search needs to be performed on the server-side.The parent component that contains the lookup must handle thesearch event:

    <c-lookuponsearch={handleSearch}label="Search"placeholder="Search Salesforce"></c-lookup>

    Thesearch event handler calls the Apexsearch method and passes the results back to the lookup using thesetSearchResults(results) function:

    asynchandleSearch(event){constlookupElement=event.target;try{constresults=awaitapexSearch(event.detail);lookupElement.setSearchResults(results);}catch(error){// TODO: handle error}}

Handling selection changes (optional)

The lookup component exposes aselectionchange event that is fired when the selection of the lookup changes.The parent component that contains the lookup can handle theselectionchange event:

<c-lookuponsearch={handleSearch}onselectionchange={handleSelectionChange}label="Search"placeholder="Search Salesforce"></c-lookup>

Theselectionchange event handler can then get the current selection from the event detail or by calling thegetSelection() function:

handleSelectionChange(event){// Get the selected ids from the event (same interface as lightning-input-field)constselectedIds=event.detail;// Or, get the selection objects with ids, labels, icons...constselection=event.target.getSelection();// TODO: do something with the lookup selection}

getSelection() always return a list of selected items.That list contains a maximum of one element if the lookup is a single-entry lookup.

Providing default search results (optional)

The lookup can return default search results with thesetDefaultResults(results) function. This is typically used to return a list of recently viewed records (see sample app).

Here's how you can retrieve recent records and set them as default search results:

  1. Implement an Apex endpoint that returns the recent records:

    @AuraEnabled(cacheable=truescope='global')publicstaticList<LookupSearchResult>getRecentlyViewed()

    See thefull code from the sample app

  2. In your parent component, create a property that holds the default results:

    recentlyViewed=[];
  3. Write a utility function that sets your default search results:

    initLookupDefaultResults(){// Make sure that the lookup is present and if so, set its default resultsconstlookup=this.template.querySelector('c-lookup');if(lookup){lookup.setDefaultResults(this.recentlyViewed);}}
  4. Retrieve the recent records by calling your endpoint:

    @wire(getRecentlyViewed)getRecentlyViewed({ data}){if(data){this.recentlyViewed=data;this.initLookupDefaultResults();}}
  5. Initialize the lookup default results when the parent component loads:

    connectedCallback(){this.initLookupDefaultResults();}

Note

TheinitLookupDefaultResults() function is called in two places because the wire could load before the lookup is rendered.

Saving form state when creating new records (optional)

The lookup component allows the user to create new record thanks to the optionalnewRecordOptions attribute. When users create a new record, they navigate away to the record edit form and they lose their current form input (lookup selection and more).

To prevent that from happening, you may provide an optional callback that lets you store the lookup state before navigating away. To do that, initialize the lookup new record options with apreNavigateCallback when the parent component loads:

connectedCallback(){/**     * This callback is called before navigating to the new record form     *@param selectedNewRecordOption the new record option that was selected     *@return Promise - once resolved, the user is taken to the new record form     */constpreNavigateCallback=(selectedNewRecordOption)=>{returnnewPromise((resolve)=>{// TODO: add some preprocessing (i.e.: save the current form state)// Always resolve the promise otherwise the new record form won't show upresolve();});};// Assign new record options with the pre-navigate callback to your lookupthis.newRecordOptions=[{value:'Account',label:'New Account', preNavigateCallback},{value:'Opportunity',label:'New Opportunity', preNavigateCallback}];}

Tip

Consider working with cookies to store information in a temporary state with an expiry date.

Passing custom data to JavaScript and Apex (optional)

Sometimes, you may want to pass extra data from the lookup component to Apex. To do so, usedataset attributes:

  1. In the parent component that uses the lookup, add a dataset attribute (data-custom in this example):

    <c-lookupselection={initialSelection}onsearch={handleLookupSearch}label="Search"is-multi-entry={isMultiEntry}data-custom="My custom value">
  2. In the parent JS, use the dataset attribute that you just added:

    handleLookupSearch(event){constlookupElement=event.target;alert(lookupElement.dataset.custom);// My custom value// Actual search code}

Reference

Attributes

AttributeTypeDescriptionDefault
disabledBooleanWhether the lookup selection can be changed.false
errors[{ "id": String, "message": String }]List of errors that are displayed under the lookup. When passing a non-empty list, the component is blurred.[]
isMultiEntryBooleanWhether the lookup is single (default) or multi entry.false
labelStringOptional (but recommended) lookup label. Label is hidden if attribute is omitted but this breaks accessibility. If you don't want to display it, we recommend to provide a label but hide it withvariant="label-hidden".''
minSearchTermLengthNumberMinimum number of characters required to perform a search.2
newRecordOptions[{ "value": String, "label": String, "defaults": String, "preNavigateCallback": Function }]List of options that lets the user create new records.
value is an sObject API name (i.e.: "Account")
label is the label displayed in the lookup (i.e.: "New Account").
defaults is an optional comma-separated list of default field values (i.e.: "Name=Foo,Type__c=Bar")
preNavigateCallback is an optional callback used forsaving the form state before navigating to the new record form.
[]
placeholderStringLookup placeholder text.''
requiredBooleanWhether the lookup is a required field. Note: Property can be set with<c-lookup required>.false
scrollAfterNItemsNumberA null or integer value used to force overflow scroll on the result listbox after N number of items.
Valid values arenull,5,7, or10.
Usenull to disable overflow scrolling.
null
selection[LookupSearchResult] ORLookupSearchResultLookup initial selection if any. Array for multi-entry lookup or an Object for single entry lookup.[]
validity{ "valid": Boolean }Read-only property used for datatable integration. Reports whether there are errors or not (seeerrors).false
value[LookupSearchResult] ORLookupSearchResultRead-only property used for datatable integration. Alias ofselection.false
variantStringChanges the appearance of the lookup. Accepted variants:
label-stacked - places the label above the lookup.
label-hidden - hides the label but make it available to assistive technology.
label-inline - aligns horizontally the label and lookup.
label-stacked

Functions

FunctionDescription
focus()Places focus on the component an opens the search dropdown (unless this is a single selection lookup with a selection).
blur()Removes focus from the component and closes the search results list.
getSelection()Gets the current lookup selection as an array ofLookupSearchResult.
setDefaultResults(results)Allows to set optional default items returned when search has no result (ex: recent items).
results is an array ofLookupSearchResult.
setSearchResults(results)Passes a search result array back to the lookup so that they are displayed in the dropdown.
results is an array ofLookupSearchResult.

Events

EventDescriptionevent.detail Type
searchEvent fired when a search needs to be performed on the server-side.
searchTerm is the sanitized (lowercase, trimmed...) search term that should be sent to the server.
rawSearchTerm is the unsanitized user input.
selectedIds is an array of selected record Ids.
{ searchTerm: String, rawSearchTerm: String, selectedIds: [ String ] }
selectionchangeEvent fired when the selection of the lookup changes. The event'sdetail property holds the list of selected ids.
You can also usetarget.getSelection() to retrieve the selected lookup objects.
[ String ]

Special use cases

Working with picklists values

The lookup component can also be used to select values from picklist fields.

This Apex sample example demonstrates how you can query for the values ofAccount.Industry:

@AuraEnabled(cacheable=truescope='global')publicstaticList<LookupSearchResult>search(StringsearchTerm,List<String>selectedIds) {// Prepare query parameterssearchTerm='%'+searchTerm+'%';// Execute search queryList<PicklistValueInfo>entries= [SELECTLabel,ValueFROMPicklistValueInfoWHEREEntityParticle.EntityDefinition.QualifiedApiName='Account'ANDEntityParticle.QualifiedApiName='Industry'ANDisActive=TRUEANDLabelLIKE:searchTermANDValueNOT IN:selectedIdsLIMIT5    ];// Prepare resultsList<LookupSearchResult>results=newList<LookupSearchResult>();for (PicklistValueInfoentry:entries) {results.add(newLookupSearchResult(entry.Value,null,null,entry.Label,null));    }returnresults;}

About

Salesforce Lookup Component built with Lightning Web Components.

Topics

Resources

License

Stars

Watchers

Forks

Contributors17


[8]ページ先頭

©2009-2025 Movatter.jp