Concepts or coding lessons of Salesforce that you can implement easily

How to pass parameters in @wire method in LWC

 Syntax :

@wire(ApexMethodName, {key: value})

for example:

@wire(getAllCases, {strOrigin :'$sampleOrigin'})

here while assigning value to variable, in our example (sampleOrigin) we have to add '$' to bind value before sending to Apex.


Create Apex class : CaseController

public with sharing class CaseController {
    @AuraEnabled(cacheable= true)
    public static List<Case> getAllCases(String strOrigin){
        try {
             List<Case> lstCase = [SELECT Id, Subject, Origin
                                FROM Case WHERE Origin=: strOrigin];
             return lstCase;
        } catch (Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }
}

wireMethod.html

<template>
    <lightning-card title="All Cases" icon-name="standard:case" variant="base">
     <div>
        <lightning-input type="text" value ={sampleOrigin}
        label="Search" onchange={handleChange}></lightning-input>      
     </div>
      <div>
        <!-- Card Body  -->
        <template for:each={records} for:item="objItem">
            <p key={objItem.Id}>
                {objItem.Subject} <br/> {objItem.Origin}
            </p>
        </template>
        <template if:true={errors}>
            Something goes wrong.
        </template>
      </div>
    </lightning-card>
</template>

wireMethod.js

import { LightningElement, wire, api, track } from 'lwc';
import getAllCases from '@salesforce/apex/CaseController.getAllCases';
export default class WireMethod extends LightningElement {
    @api records;
    @api errors;
    @
track sampleOrigin;
    
    handleChange(event){
        const temp = event.target.value;
        this.sampleOrigin = temp;
    }

    /*
        @wire(ApexMethodName, {key: value})
            wiredCase ({ data, error }){
                - data => return list of case
                - error => error in for, of object
            }
    */
   @wire(getAllCases, {
        strOrigin :'$sampleOrigin'
    })
            wiredCase ({
                data, error
            }){
                if(data){
                    this.records = data;
                    this.errors = undefined;
                }
                if(error){
                    this.records = undefined;
                    this.errors = error;
                }
            }
}


Subscribe blog for More updates !!! 


Read More: WhatsApp on Salesforce Integration in 5 Steps
                    Which Salesforce API Do I Use in Integration?
                    When To Use Salesforce REST API  
                   When To Use Salesforce SOAP API 
                   When To Use Salesforce Bulk API 


Latest Salesforce Interview Questions and Answers:

loading...

No comments:

Post a Comment