Generic Custom Lookup Lightning Web Component
Hello Trailblazers,
In this blog I have created generic lookup component using LWC which can be used directly without changing single line of code. You just have to pass object name, fields to be retrieved and fieldname on which search operation should happen while using this component along with event handler method, that’s it you are ready to use record captured in lookup field. Which makes it available for use multiple times in single component.
This example contains below main components :
1. GenericLookup – Apex class for querying records
2. genericLookup - LWC Main component - This you will be using as per your need
3. recordListItem - LWC to render suggested records
First lets have a look at GenericLookup class
Now create recordListItem component
And finally genericLookup component
This component basically gets the input from user as search value and makes call to apex whenever search-key length is greater than 3(you can change this value as per your logic). Once records are received, recordListItem is used initeration to display the records. This component also handles the event fired by recordListItem component upon selection from user.
Now how to use this in your component ? Few simple steps ...
Copy paste below code to your desired place, change attributes, write handler method and done !
- search-field : This should be replaced by the field name on which you wish to apply filter
- retrieve-fields : String with field names separated by "," (Name,AccountId,CustomField__c)
- object-name : Name of object
- field-label : Label you want to give to lookup field
- onselectrecord : Event that needs to be handled. Get data using "event.detail", this will give you entire record that is selected.
Note : Do not use Id field in retrieve-fields attribute as it is already mentioned in Apex class, you can directly use it.
This way you can use this component as many times in your single component.
You can code from Github as well.
This way you can use this component as many times in your single component.
You can code from Github as well.
Please share your feedback/concerns by commenting.
Thank You !!
Comments
Post a Comment