Sunday, June 14, 2020

Access sObject Values With Static Schema Definition in Apex

Access sObject Values With Static Schema Definition in Apex

Hello Guys, Hope everybody is taking care of themselves and doing great! In this blog, we will be going to learn how to access records of an sObject using static schema. We will call an apex method and access sObject values using a static schema definition.

Example- In this example , we are going to access Name, Title, Email and Phone field from contact object. So let's start doing this-

First we are going to create Aura Enabled method to get Name, Title, Email and phone field from contact.

ContactController.cls
public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static Contact getSingleContact() {
        return [
            SELECT IdNameTitlePhoneEmail
            FROM Contact
            LIMIT 1
        ];
    }
}

apexStaticScemaExample.html
<template>
    <lightning-card title="ApexStaticSchemaExample" 
   icon-name="custom:custom63">
        <template if:true={contact.data}>
            <div class="slds-m-around_medium">
                <p>Name  : {name}</p>
                <p>Title : {title}</p>
                <p>Email :
                    <lightning-formatted-email
                        value={email}
                    ></lightning-formatted-email>
                </p>
                <p>Phone : {phone}</p>
            </div>
        </template>
        <template if:true={contact.error}>
            <p> errors={contact.error}> </p>
        </template>
    </lightning-card>
</template>

The above code is used just to show the value of fields on screen.
Name, title ,email, phone are the getter methids in the js file , which are returnig the corresponding value from the contact property that have been populated by wire service.

apexStaticScemaExample.js
import { LightningElementwire } from 'lwc';
import { getSObjectValue } from '@salesforce/apex';
import getSingleContact from 
       '@salesforce/apex/ContactController.getSingleContact';

import NAME_FIELD from '@salesforce/schema/Contact.Name';
import TITLE_FIELD from '@salesforce/schema/Contact.Title';
import EMAIL_FIELD from '@salesforce/schema/Contact.Email';
import PHONE_FIELD from '@salesforce/schema/Contact.Phone';

export default class ApexStaticSchemaExample extends LightningElement {
    @wire(getSingleContactcontact;

    get name() {
        return this.contact.data
            ? getSObjectValue(this.contact.dataNAME_FIELD)
            : '';
    }
    get title() {
        return this.contact.data
            ? getSObjectValue(this.contact.dataTITLE_FIELD)
            : '';
    }
    get email() {
        return this.contact.data
            ? getSObjectValue(this.contact.dataEMAIL_FIELD)
            : '';
    }
    get phone() {
        return this.contact.data
            ? getSObjectValue(this.contact.dataPHONE_FIELD)
            : '';
    }
}


import { getSObjectValue } from '@salesforce/apex';
It is used as we are using standard getSObjectValue method to get the value of a field from a sObjects record , so we need to import it from the apex folder.

import getSingleContact from '@salesforce/apex/ContactController
.getSingleContact';
This is used to access the aura enabled method from the ContactController apex class.

import NAME_FIELD from '@salesforce/schema/Contact.Name';
Used to import references of field from object.

Notes-
If a component gets an object via an Apex class and imports references to the object from @salesforce/schema, call getSObjectValue() to get a field value from the object.

Now Let's make this component available on App Page, Home Page and Record Page.

apexStaticScemaExample.js-meta.xml
<?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__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Output-


Thanks for reading and happy learning😃.
Stay tuned for next Post.
Keep sharing , keep learning.

CS- D G.

Saturday, June 6, 2020

Call server side method Imperatively in LWC(Lightning web component)

Different ways to access server side controller method from LWC component
  1. Wire a property
  2. Wire a function
  3. Call a method imperatively
1- Wire a property- 
    
This is already explained in my previous blog post. Those who want to revise or have not gone through previous post can go through this Link

2- Wire a function-

This is already explained in my previous blog post. Those who want to revise or have not gone through previous post can go through this Link

3- Call a method imperatively-

Calling a method imperatively means you control when the invocation occurs (for example, in response to clicking a button).When you call a method imperatively, you receive only a single response.

Now Let's take an example and understand it. In this we are going to create a component having Button and on click of button , we will fetch contacts record.

imperativeMethodExample.html

<template>
    <lightning-card title="imperativeMethodExample" icon-name="custom:custom63">
        <div class="slds-m-around_medium">
            <p class="slds-m-bottom_small">
                <lightning-button
                    label="Load Contacts"
                    onclick={handleLoad}
                ></lightning-button>
            </p>
            <template if:true={contacts}>
                <template for:each={contacts} for:item="contact">
                    <p key={contact.Id}>{contact.Name}</p>
                </template>
            </template>
            <template if:true={error}>
                <p errors={error}></p>
            </template>
        </div>
    </lightning-card>
</template>

imperativeMethodExample.js

import { LightningElement } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class ImperativeMethodExample extends LightningElement {
    contacts;
    error;

    handleLoad() {
        getContactList()
            .then((result=> {
                this.contacts = result;
                this.error = undefined;
            })
            .catch((error=> {
                this.error = error;
                this.contacts = undefined;
            });
    }
}

Adding the configuration file details so that you can expose the component in your org through app builder.

imperativeMethodExample.js-meta.xml-

<?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__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>


ContactController.cls

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<ContactgetContactList() {
        return [
            SELECT IdNameTitlePhoneEmail
            FROM Contact
            WITH SECURITY_ENFORCED
            LIMIT 10
        ];
    }
}

Output when Button is clicked -


Thanks for reading and happy learning😃.
Stay tuned for next Post.
Keep sharing , keep learning.

CS- Dev Guide

Saturday, May 9, 2020

Call server side method using Wiring a function in LWC(Lightning web component)

Different ways to access server side controller method from LWC component
  1. Wire a property
  2. Wire a function
  3. Call a method imperatively
1- Wire a property- 
    
This is already explained in my previous blog post. Those who want to revise or have not gone through previous post can go through this link .


In this post we are going to discuss how we can access server side controller using -

2- Wire a function-

In this component wires an Apex method call to a function. Because the results are provisioned to a function, the JavaScript can operate on the results. Also, the template accesses the data a bit differently than if results were provisioned to a property.

The rendered component is the same as apexWireMethodToProperty (except for the header).
This component calls the same Apex method as apexWireMethodToProperty. The method must be static, and global or public. The method must be decorated with @AuraEnabled(cacheable=true).


Let’s use the same example which I used in my previous blog that is displaying the contacts name getting from server side method of controller class.


LWCWireMethodToFunction.html

<template>
    <lightning-card
        title="LWCWireMethodToFunction"
        icon-name="custom:custom63">
    
        <div class="slds-m-around_medium">
            <template if:true={contacts}>
                <template for:each={contacts} for:item="contact">
                    <p key={contact.Id}>{contact.Name}</p>
                </template>
            </template>
            <template if:true={error}>
                <c-error-panel errors={error}></c-error-panel>
            </template>
        </div>
    </lightning-card>

</template>

The template uses the if:true directive to check for the JavaScript contacts property. If it exists, it iterates over it and renders the name of each contact. If the error property exists, the component renders <c-error-panel>.


LWCWireMethodToFunction.js

import { LightningElement, wire } from 'lwc';
import getContactList from '@salesforce/apex/ContactController.getContactList';

export default class LWCWireMethodToFunction extends LightningElement {
    contacts;
    error;

    @wire(getContactList)
    wiredContacts({ error, data }) {
        if (data) {
            this.contacts = data;
            this.error = undefined;
        } else if (error) {
            this.error = error;
            this.contacts = undefined;
        }
    }

}

The component’s JavaScript code imports the Apex method and invokes it via the wire service. The wire service provisions the results to the wiredContacts() function via an object with either an error or data property. If the wire service provisions data, it’s assigned to this.contacts, which is used in the template. If it provisions error, it’s assigned to this.error, which is also used in the template. If the value of these properties change, the template rerenders.


ContactController.cls

public with sharing class ContactController {
    @AuraEnabled(cacheable=true)
    public static List<Contact> getContactList() {
        return [
            SELECT Id, Name, Title, Phone, Email, Picture__c
            FROM Contact
            WHERE Picture__c != null
            WITH SECURITY_ENFORCED
            LIMIT 10
        ];
    }

}
O/p-
              LWCWireMethodToFunction
                Amy Taylor
                Michael Jones
                Jennifer Wu
                Anup Gupta

                Caroline Kingsl


Thanks for reading and happy learning😃.

Stay tuned for next Post- calling server side method imperatively.


CS- LWC Recipe