import { LightningElement,api,wire} from 'lwc';
import searchLookupData from '@salesforce/apex/CustomLookup.searchLookupData';
import searchDefaultRecord from '@salesforce/apex/CustomLookup.searchDefaultRecord';
export default class CustomLookup extends LightningElement {
// public properties with initial default values
@api label = 'label';
@api placeholder = 'search...';
@api iconName = 'standard:contact';
@api sObjectApiName = 'Contact';
@api defaultRecordId = '';
@api accountId = '001E200000A2JaKIAV';
// private properties
lstResult = []; // to store list of returned records
hasRecords = true;
searchKey =''; // to store input field value
isSearchLoading = false; // to control loading spinner
delayTimeout;
isValueSelected;
selectedRecord = {}; // to store selected lookup record in object formate
@api filterByAccountId(accountId) {
this.accountId = accountId;
this.searchKey = ''; // Clear any existing search key
this.getData();
}
getData() {
searchLookupData({ searchKey: this.searchKey, sObjectApiName: this.sObjectApiName, accountId: this.accountId })
.then((result) => {
if (result) {
this.hasRecords = result.length > 0;
this.lstResult = result;
}
})
.catch((error) => {
console.error('Error retrieving data:', error);
});
}
// initial function to populate default selected lookup record if defaultRecordId provided
connectedCallback(){
if(this.defaultRecordId != ''){
searchDefaultRecord({ recordId: this.defaultRecordId , 'sObjectApiName' : this.sObjectApiName })
.then((result) => {
if(result != null){
this.selectedRecord = result;
this.handelSelectRecordHelper(); // helper function to show/hide lookup result container on UI
}
})
.catch((error) => {
this.error = error;
this.selectedRecord = {};
});
}
}
// wire function property to fetch search record based on user input
@wire(searchLookupData, { searchKey: 'searchKey′,sObjectApiName:′sObjectApiName' })
searchResult(value) {
const { data, error } = value; // destructure the provisioned value
this.isSearchLoading = false;
if (data) {
this.hasRecords = data.length == 0 ? false : true;
this.lstResult = JSON.parse(JSON.stringify(data));
}
else if (error) {
console.log('(error---> ' + JSON.stringify(error));
}
};
// update searchKey property on input field change
handleKeyChange(event) {
// Do not update the reactive property as long as this function is
this.isSearchLoading = true;
window.clearTimeout(this.delayTimeout);
const searchKey = event.target.value;
this.delayTimeout = setTimeout(() => {
this.searchKey = searchKey;
}, 300);
}
// method to toggle lookup result section on UI
toggleResult(event){
const lookupInputContainer = this.template.querySelector('.lookupInputContainer');
const clsList = lookupInputContainer.classList;
const whichEvent = event.target.getAttribute('data-source');
switch(whichEvent) {
case 'searchInputField':
clsList.add('slds-is-open');
break;
case 'lookupContainer':
clsList.remove('slds-is-open');
break;
}
}
// method to clear selected lookup record
handleRemove(){
this.searchKey = '';
this.selectedRecord = {};
this.lookupUpdateParenthandler(undefined); // update value on parent component as well from helper function
this.isValueSelected = false;
}
// update selected record from search result
handelSelectedRecord(event){
var objId = event.target.getAttribute('data-recid'); // get selected record Id
this.selectedRecord = this.lstResult.find(data => data.Id === objId); // find selected record from list
this.lookupUpdateParenthandler(this.selectedRecord); // update value on parent component
this.handelSelectRecordHelper(); // helper function to show/hide lookup result container on UI
}
//handle select record
handelSelectRecordHelper(){
this.template.querySelector('.lookupInputContainer').classList.remove('slds-is-open');
this.isValueSelected = true;
}
// send selected lookup record to parent component using custom event
lookupUpdateParenthandler(value){
console.log(value);
const oEvent = new CustomEvent('lookupupdate',
{
'detail': {selectedRecord: value}
}
);
this.dispatchEvent(oEvent);
}
} import { LightningElement, api, track, wire } from 'lwc';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import LEAD_OBJECT from '@salesforce/schema/Opportunity';
import getLeadForId from '@salesforce/apex/LeadController.getLeadForId';
import saveOpportunityData from '@salesforce/apex/OpportunityController.saveOpportunityData';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import strUserId from '@salesforce/user/Id';
import { CurrentPageReference } from 'lightning/navigation';
import { CloseActionScreenEvent } from 'lightning/actions';
import CustomLookup from 'c/customLookup';
export default class PartnerOpportunityCreation extends LightningElement {
@track closeDate = new Date();
@track opportunityName = '';
amount = '';
company = '';
currencyIsoCode = '';
accountId = '001E200000A2JaKIAV';
accountName = 'Account';
contactId = '';
contactName = '';
stageName = 'Prospecting';
relatedLeadId = '';
leadOptions = [];
@api recordId;
userId = strUserId;
// Getter and setter for default Close Date
get defaultCloseDateValue() {
const today = new Date();
const twoWeeksFromNow = new Date(today.getTime() + (14 * 24 * 60 * 60 * 1000)); // Adding 2 weeks (14 days) to today’s date
this.closeDate = twoWeeksFromNow.toISOString().split('T')[0];
return this.closeDate;
}
set defaultCloseDateValue(value) {
this.closeDate = value;
}
// Getter and setter for default Opportunity Name
get defaultOpportunityNameValue() {
this.opportunityName = ${this.company} from ${this.accountName}; // Combining Company field value from Lead and Partner Account Name value from Account
return this.opportunityName;
}
set defaultOpportunityNameValue(value) {
this.opportunityName = value;
}
handleAccountLookupSelection(event){
if(event.detail.selectedRecord != undefined){
this.accountName = event.detail.selectedRecord.Name;
this.accountId = event.detail.selectedRecord.Id;
// Pass the selected Account Id to the custom lookup component
const contactLookup = this.template.querySelector('.customLookupContact');
if (contactLookup) {
// Filter contacts based on the selected AccountId
contactLookup.filterByAccountId(this.accountId);
}
}
}
handleContactLookupSelection(event){
if(event.detail.selectedRecord != undefined){
this.contactName = event.detail.selectedRecord.Name;
this.contactId = event.detail.selectedRecord.Id;
}
}
handleAmountChange(event) {
this.amount = parseFloat(event.detail.value);
}
handleCloseDateChange(event) {
this.closeDate = new Date(event.detail.value);
}
handleOpportunityNameChange(event) {
this.opportunityName = event.detail.value;
}
@wire(getObjectInfo, { objectApiName: LEAD_OBJECT })
objectInfo;
@wire(CurrentPageReference)
async getStateParameters(currentPageReference) {
try {
if (currentPageReference) {
this.recordId = currentPageReference.state.recordId;
this.relatedLeadId = this.recordId;
}
const resultLeads = await getLeadForId({ recordId: this.recordId });
const selectedLead = resultLeads.find(
(lead) => lead.Id === this.recordId
);
if (selectedLead) {
this.company = selectedLead.Company;
} else {
console.error('Lead not found for recordId:', this.recordId);
}
} catch (error) {
console.error('Error loading data:', error.message);
}
}
async submitData() {
try {
await saveOpportunityData({
id: this.recordId,
accountId: this.accountId,
closeDate: this.closeDate,
opportunityName: this.opportunityName,
amount: this.amount,
stageName: this.stageName,
currencyIsoCode: this.currencyIsoCode,
relatedLeadId: this.relatedLeadId,
introducedById: this.contactId
});
this.showSuccessToast('Partner Opportunity created successfully');
this.dispatchEvent(new CloseActionScreenEvent());
} catch (error) {
this.showErrorToast(error.body.message);
}
}
handleCancel() {
this.dispatchEvent(new CloseActionScreenEvent());
}
showSuccessToast(message) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Success',
message: message,
variant: 'success',
})
);
}
showErrorToast(message) {
this.dispatchEvent(
new ShowToastEvent({
title: 'Error',
message: message,
variant: 'error',
})
);
}
} How to fix this code so the contact lightning input show only records which accountId equal default-record-id of account lightning input