function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Saurav Roy 15Saurav Roy 15 

Imperative Method LWC

Hi All,

Could you please look into the code and let me know where i am wrong.
I am trying the retrieve the list of accounts using imperative method. The data is not retrieving and it the going to the catch error block.
 
Apex Class
public with sharing class ContactListService {
@AuraEnabled
    public static List<Object> getAcountList(String name){
        String key = '%'+name+'%';
        String accQuery = 'select id, name, email, phone from Account where name like : key';
        System.debug('Query --- '+Database.query(accQuery));
        return Database.query(accQuery);
        
    }
}

JS File:
import { LightningElement, track } from 'lwc';
import getAcountList from '@salesforce/apex/ContactListService.getAcountList';
export default class ContactList extends LightningElement {
    
    @track accounts;
    @track errorAccount;
    @track searchAccount;

    handleChangeAccount(event){
        //event.preventDefault();
        console.log('Value '+event.target.value);
        this.searchAccount = event.target.value;
    }
    
    //Imperative method
    findaccounts(){
        getAcountList({
		name : this.searchAccount
	})
        .then(result =>{
            console.log('Result----'+result);
                this.accounts = result;
        })
        .catch(error=>{
                this.errorAccount = error;
                console.log('Error ----'+error);
        });
    }
}


HTML:
<template>
	<lightning-card>
	    <lightning-layout vertical-align="center">
                  <lightning-layout-item padding="around-small">
                      <lightning-input label="Find Account" value={searchAccount} onchange={handleChangeAccount}></lightning-input>
            	</lightning-layout-item>
            
		<lightning-layout-item padding="around-small">
                	<lightning-button label="Find Accounts" varient="brand" onclick={findaccounts}></lightning-button>
           	</lightning-layout-item>
    
            	<lightning-layout-item padding="around-small">
                	<template for:each={accounts} for:item="acc">
                    		<p key={acc.id}>{acc.Name}</p>
        		</template>
            	</lightning-layout-item>
            </lightning-layout>
	</lightning-card>
</template>

User-added image

Thanks
Saurav
 
Best Answer chosen by Saurav Roy 15
Maharajan CMaharajan C
HI Saurav,

1. In account object we don't have standard field Email. So remove email field from apex query.

2. In Lightning Button change spalling for varient="brand"  => variant="brand"

3. use the if:true  Accounts check in template before the for each. 

4. i have updated your template code to fix the alignments.

5. use the acc.Id in Key for <p>. here letter(i) should be in caps.

Updated Code Below:

Apex Class:
public with sharing class ContactListService {
@AuraEnabled
    public static List<Object> getAcountList(String name){
        String key = '%'+name+'%';
        String accQuery = 'select id, name, phone from Account where name like : key';
        System.debug('Query --- '+Database.query(accQuery));
        return Database.query(accQuery);
        
    }
}

HTML File:
<template>
	<lightning-card>
	    <lightning-layout vertical-align="center" multiple-rows="true">
                  <lightning-layout-item padding="around-small" size="12" small-device-size="10" medium-device-size="8" large-device-size="6">
                      <lightning-input label="Find Account" value={searchAccount} onchange={handleChangeAccount}></lightning-input>
            	</lightning-layout-item>
                
		<lightning-layout-item padding="around-small" class="slds-m-top_large" size="12" small-device-size="4" medium-device-size="4" large-device-size="4">
                	<lightning-button label="Find Accounts" variant="brand" onclick={findaccounts}></lightning-button>
        </lightning-layout-item>
    
        <lightning-layout-item padding="around-small" size="12" small-device-size="12" medium-device-size="12" large-device-size="12">
            <template if:true={accounts}>
                <template for:each={accounts} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
        </lightning-layout-item>
        </lightning-layout>         
    </lightning-card>
</template>

JS File:  No update in JS
 
import { LightningElement,track } from 'lwc';
import getAcountList from '@salesforce/apex/ContactListService.getAcountList';

export default class ForumContactListService extends LightningElement {

    @track accounts;
    @track errorAccount;
    @track searchAccount;

    handleChangeAccount(event){
        //event.preventDefault();
        console.log('Value '+event.target.value);
        this.searchAccount = event.target.value;
    }
    
    //Imperative method
    findaccounts(){
        getAcountList({
		name : this.searchAccount
	    })
        .then(result =>{
            console.log('Result----'+result);
                this.accounts = result;
        })
        .catch(error=>{
                this.errorAccount = error;
                console.log('Error ----'+error);
        });
    }
}

XML File:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>




Thanks,
Maharajan.C

 

All Answers

Maharajan CMaharajan C
HI Saurav,

1. In account object we don't have standard field Email. So remove email field from apex query.

2. In Lightning Button change spalling for varient="brand"  => variant="brand"

3. use the if:true  Accounts check in template before the for each. 

4. i have updated your template code to fix the alignments.

5. use the acc.Id in Key for <p>. here letter(i) should be in caps.

Updated Code Below:

Apex Class:
public with sharing class ContactListService {
@AuraEnabled
    public static List<Object> getAcountList(String name){
        String key = '%'+name+'%';
        String accQuery = 'select id, name, phone from Account where name like : key';
        System.debug('Query --- '+Database.query(accQuery));
        return Database.query(accQuery);
        
    }
}

HTML File:
<template>
	<lightning-card>
	    <lightning-layout vertical-align="center" multiple-rows="true">
                  <lightning-layout-item padding="around-small" size="12" small-device-size="10" medium-device-size="8" large-device-size="6">
                      <lightning-input label="Find Account" value={searchAccount} onchange={handleChangeAccount}></lightning-input>
            	</lightning-layout-item>
                
		<lightning-layout-item padding="around-small" class="slds-m-top_large" size="12" small-device-size="4" medium-device-size="4" large-device-size="4">
                	<lightning-button label="Find Accounts" variant="brand" onclick={findaccounts}></lightning-button>
        </lightning-layout-item>
    
        <lightning-layout-item padding="around-small" size="12" small-device-size="12" medium-device-size="12" large-device-size="12">
            <template if:true={accounts}>
                <template for:each={accounts} for:item="acc">
                    <p key={acc.Id}>{acc.Name}</p>
                </template>
            </template>
        </lightning-layout-item>
        </lightning-layout>         
    </lightning-card>
</template>

JS File:  No update in JS
 
import { LightningElement,track } from 'lwc';
import getAcountList from '@salesforce/apex/ContactListService.getAcountList';

export default class ForumContactListService extends LightningElement {

    @track accounts;
    @track errorAccount;
    @track searchAccount;

    handleChangeAccount(event){
        //event.preventDefault();
        console.log('Value '+event.target.value);
        this.searchAccount = event.target.value;
    }
    
    //Imperative method
    findaccounts(){
        getAcountList({
		name : this.searchAccount
	    })
        .then(result =>{
            console.log('Result----'+result);
                this.accounts = result;
        })
        .catch(error=>{
                this.errorAccount = error;
                console.log('Error ----'+error);
        });
    }
}

XML File:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
    <apiVersion>48.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__RecordPage</target>
        <target>lightning__AppPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>




Thanks,
Maharajan.C

 
This was selected as the best answer
Saurav Roy 15Saurav Roy 15
Thanks Maharajan
Lukesh KarmoreLukesh Karmore
connectedCallback is missing in Imperative method