Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

But where should i do it, in CustomLookup component css file directly or in…

  1. User

    But where should i do it, in CustomLookup component css file directly or in PartnerOpportunityCreation component css file?

  2. Assistant

    It depends on your specific requirements and the structure of your components.

    If the styles you want to apply are only relevant to the CustomLookup component, it would make sense to add them directly to the CustomLookup component's CSS file. This keeps the styles encapsulated within the component and makes it easier to manage and maintain.

    However, if the styles should be applied across multiple components, or if the styles are related to the overall layout and design of the PartnerOpportunityCreation component, it would be more appropriate to add them to the PartnerOpportunityCreation component's CSS file.

    Ultimately, the decision will depend on the specific context and requirements of your application.

  3. User

    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:′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

  4. Assistant

    To fix the code and ensure that the Contact lightning input only shows records with an AccountId equal to the default-record-id of the Account lightning input, you need to make the following modifications:

    1. Update the CustomLookup component:

      • Add a new property accountId to the CustomLookup component and set it as an @api property.
      • In the getData method, modify the query to include a filter by accountId.
      • In the handleKeyChange method, add a condition to clear the search key if the accountId changes.
      • Update the filterByAccountId method to set the accountId property and call the getData method.

      Here's the updated code for the CustomLookup component:

    // import statements
    
    export default class CustomLookup extends LightningElement {
        // public properties and private properties
    
        @api accountId = ''; // new property for the Account Id
    
        // getData and other methods
    
        filterByAccountId(accountId) {
            this.accountId = accountId; // set the accountId property
            this.searchKey = ''; // clear any existing search key
            this.getData(); // call the getData method with the updated accountId
        }
    
        // wire function and other methods
    }
    
    1. Update the PartnerOpportunityCreation component:

      • Import the CustomLookup component using the correct import statement import CustomLookup from 'c/customLookup';.
      • Add a new method handleAccountLookupSelection to handle the selection of the Account in the Account lightning input.
      • In the handleAccountLookupSelection method, get a reference to the Contact lightning input using this.template.querySelector and then call the filterByAccountId method on the CustomLookup component, passing the selected Account Id.
      • Add the onlookupupdate event handler to the CustomLookup component and handle the Contact selection in the handleContactLookupSelection method.

      Here's the updated code for the PartnerOpportunityCreation component:

    // import statements
    
    export default class PartnerOpportunityCreation extends LightningElement {
        // public properties, tracked properties, and other code
    
        handleAccountLookupSelection(event) {
            // handle the selection of Account in Account lightning input
            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) {
            // handle the selection of Contact in Contact lightning input
            if (event.detail.selectedRecord != undefined) {
                this.contactName = event.detail.selectedRecord.Name;
                this.contactId = event.detail.selectedRecord.Id;
            }
        }
    
        // other methods and code
    }
    

    With these modifications, the Contact lightning input will only show records that have an AccountId equal to the selected value in the Account lightning input.

  5. User

    But how to add logic to this code if Account record in lightning input is selected by default, also filer contacts in contact lightning input for this default account

  6. Assistant

    To add logic for selecting the default Account record in the lightning input and filtering the contacts in the Contact lightning input based on the default Account, you can make the following modifications:

    1. Update the PartnerOpportunityCreation component's handleAccountLookupSelection method to check if the selected Account is the default one. If it is, set the default Account values and filter the contacts accordingly.
    handleAccountLookupSelection(event) {
        if (event.detail.selectedRecord != undefined) {
            this.accountName = event.detail.selectedRecord.Name;
            this.accountId = event.detail.selectedRecord.Id;
            if (event.detail.selectedRecord.Id === DEFAULT_ACCOUNT_ID) {
                // Set default values for Account fields
                this.contactName = DEFAULT_CONTACT_NAME;
                this.contactId = DEFAULT_CONTACT_ID;
    
                // Pass the default Account Id to the custom lookup component
                const contactLookup = this.template.querySelector('.customLookupContact');
                if (contactLookup) {
                    // Filter contacts based on the default AccountId
                    contactLookup.filterByAccountId(DEFAULT_ACCOUNT_ID);
                }
            }
        }
    }
    
    1. Add a custom event in the CustomLookup component to notify the parent component when the Account lightning input receives a default value.
    // In the CustomLookup component
    // Add this method to send a custom event when the default Account is selected
    handleDefaultAccountSelection(accountId) {
        const event = new CustomEvent('defaultaccountselected', { detail: { accountId } });
        this.dispatchEvent(event);
    }
    
    1. Update the PartnerOpportunityCreation component's template to include the custom event.
    <template>
        <!-- Account lightning input -->
        <c-custom-lookup
            label="Account"
            placeholder="Search Account"
            s-object-api-name="Account"
            onlookupupdate={handleAccountLookupSelection}
            ondefaultaccountselected={handleDefaultAccountSelection}>
        </c-custom-lookup>
    
        <!-- Contact lightning input -->
        <c-custom-lookup
            class="customLookupContact"
            label="Contact"
            placeholder="Search Contact"
            s-object-api-name="Contact"
            account-id={accountId}
            onlookupupdate={handleContactLookupSelection}>
        </c-custom-lookup>
    
        <!-- Rest of the component -->
    </template>
    
    1. Update the PartnerOpportunityCreation component's JavaScript code to handle the custom event and set the default Account values.
    // In the PartnerOpportunityCreation component
    handleDefaultAccountSelection(event) {
        const { accountId } = event.detail;
        this.accountId = accountId;
        this.contactName = DEFAULT_CONTACT_NAME;
        this.contactId = DEFAULT_CONTACT_ID;
    
        // Filter contacts based on the default AccountId
        const contactLookup = this.template.querySelector('.customLookupContact');
        if (contactLookup) {
            contactLookup.filterByAccountId(accountId);
        }
    }
    

    Make sure to replace DEFAULT_ACCOUNT_ID, DEFAULT_CONTACT_NAME, and DEFAULT_CONTACT_ID in the code snippets above with your specific default values.

    These modifications will allow the Account lightning input to select the default Account record, set the default values for the Contact lightning input, and filter the contacts based on the default Account.

  7. User

    But i need only filter the contacts based on the default Account.

  8. Assistant

    To filter the contacts in the Contact lightning input based on the default Account, you can modify the PartnerOpportunityCreation component as follows:

    1. Create a default Account variable to store the default Account details:
    defaultAccount = {
        Id: '001E200000A2JaKIAV', // Default Account Id
        Name: 'Default Account' // Default Account Name
    };
    
    1. In the handleAccountLookupSelection method, check if the selected Account matches the default Account. If it does, set the default Account values and filter the contacts in the Contact lightning input accordingly.
    handleAccountLookupSelection(event) {
        if (event.detail.selectedRecord != undefined) {
            this.accountName = event.detail.selectedRecord.Name;
            this.accountId = event.detail.selectedRecord.Id;
            if (this.accountId === this.defaultAccount.Id) {
                // Set default values for Account fields
                this.contactName = DEFAULT_CONTACT_NAME;
                this.contactId = DEFAULT_CONTACT_ID;
    
                // Filter contacts based on the default Account
                const contactLookup = this.template.querySelector('.customLookupContact');
                if (contactLookup) {
                    contactLookup.filterByAccountId(this.defaultAccount.Id);
                }
            }
        }
    }
    
    1. Update the CustomLookup component's filterByAccountId method to filter the contacts based on the provided AccountId:
    filterByAccountId(accountId) {
        this.accountId = accountId;
        this.searchKey = ''; // Clear any existing search key
        this.getData();
    }
    
    1. Finally, update the PartnerOpportunityCreation component's template to pass the default Account Id to the Contact lightning input's filterByAccountId method:
    <!-- Contact lightning input -->
    <c-custom-lookup class="customLookupContact"
        label="Contact"
        placeholder="Search Contact"
        s-object-api-name="Contact"
        account-id={defaultAccount.Id}>
    </c-custom-lookup>
    

    With these modifications, the contacts in the Contact lightning input will be filtered based on the default Account Id.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.