Sunday, February 28, 2021

How to use createRecord(recordInput) in LWC?

 Using lightning/uiRecordApi we can perform operations as mentioned below without using Apex.

1) Create a record 

2) Get record data

3) Delete a record

4) Get a field value from record

5) Update a record and etc.


In this blog post we will learn How to create record using lightning/uiRecordApi ?


Let's understand with simple example as explained below:


createRecordExampleLwc.html

<template>

    <lightning-card  title="Create Account">

        <p class="slds-p-horizontal_small">

            <lightning-input type="text" label="Enter Account name" onchange={handleAccName}></lightning-input>

        </p>

        <p slot="footer"> <lightning-button label="Create Account"  onclick={createAccount}></lightning-button></p>

      

</lightning-card>

</template>


createRecordExampleLwc.js

import { LightningElement } from 'lwc';

import { createRecord } from 'lightning/uiRecordApi';

import ACCOUNT_OBJECT from '@salesforce/schema/Account';

import ACCOUNT_NAME from '@salesforce/schema/Account.Name';

export default class CreateRecordExampleLwc extends LightningElement {

 

    accName;

    handleAccName(event){

    this.accName=event.target.value;

    }

    createAccount(){

        var fields ={'Name' : this.accName};

        const accRecord ={apiName : ACCOUNT_OBJECT.objectApiName, fields : fields};

        createRecord(accRecord)

        .then( response => {

            alert('Account Inserted and Id is'+response.id);

        })

        .catch( error =>   {

        alert('Some error occured'+JSON.stringify(error));

        });

 

    }

}


createRecordExampleLwc.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>50.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

        <target>lightning__RecordPage</target>

    </targets>

</LightningComponentBundle>



Output:

How to use createRecord(recordInput) in LWC?


How to use createRecord(recordInput) in LWC?

Sunday, February 21, 2021

How to deserializes respone in Apex using deserializeUntyped(jsonString)?

  deserializeUntyped(jsonString) deserializes the specified JSON string into collections of primitive data types.


Consider the below JSON for understanding the use of  deserializeUntyped(jsonString).

Let say we are receiving this JSON from external system and we want to write REST webservice to handle this request.


{

  "event": {

    "recorddata": {

      "state": "Success",

      "recordItem": [

        {

          "id": "1",

          "name": "testRecord1"

        },

        {

          "id": "2",

          "name": "testRecord2"

        }

      ]

    }

  }

}


In webservice class,


@RestResource(urlMapping='/postrecorddata/*')

   global with sharing class postrecorddata {

       @HttpPost

      global static responseWrapper postrecorddatamethod(){

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        Map<String,Object> map = (Map<String,Object>) JSON.deserializeUntyped(req.requestBody.toString());

        Map<String,Object> map1= (Map<String,Object>) map.get('event');

        Map<String,Object> map2= (Map<String,Object>) map1.get('recorddata');

        String stateValue = (String) map2.get('state');

        List<Object> recordItemList= (List<Object> ) map2.get('recordItem');

        // Perform Some operations and return response

        responseWrapper obj=new responseWrapper();

        obj.message='Data Posted successfully';

        obj.statusCode = '200';

        // Overriding RestResponse object value

        res.statusCode = '200';

        return obj;

        global class responseWrapper{

        global string message;

        global integer statusCode;

        }

        

      }

   }


How to deserializes respone in Apex using deserialize(jsonString, apexType)?

 deserialize(jsonString, apexType) deserializes the specified JSON string into an Apex object of the specified type.

Consider the below JSON for understanding the use of  deserialize(jsonString, apexType).

Let say we are receiving this JSON from external system and we want to write REST webservice to handle this request.

  "nameofsystem" : "ExternalSystem1",

  "event": {

    "recorddata": {

      "state": "Success",

      "recordItem": [

        {

          "id": "1",

          "name": "testRecord1"

        },

        {

          "id": "2",

          "name": "testRecord2"

        }

      ]

    }

  }

}


In webservice class,


@RestResource(urlMapping='/postrecorddata/*')

   global with sharing class postrecorddata {

       @HttpPost

      global static responseWrapper postrecorddatamethod(){

        RestRequest req = RestContext.request;

        RestResponse res = Restcontext.response;

        responeWrapper wrapObj= (responeWrapper) JSON.deserialize(req.requestbody.toString(),responeWrapper.class);

        // To get the the state from JSON response.

        String stateInResponse = wrapObj.event.recorddata.state;

        // Perform operations

        returnResponseWrapper obj=new returnResponseWrapper();

        obj.message='Data Posted successfully';

        obj.statusCode = '200';

        // Overriding RestResponse object value

        res.statusCode = '200';

        return obj;

        

      }

 

// Wrapper class for handling request

global class responeWrapper{

 global string nameofsystem;

 global eventData event;

 

}

global class eventData{

 global recorddataObj recorddata;

}

 

global class recorddataObj{

 global string state;

 global recordItemClass[] recordItem;

  

}

 

global class recordItemClass{

 global string id; 

 global string name;

}

// Wrapper class for handling request

 

// Wrapper class for response

      global class returnResponseWrapper{

        global string message;

        global integer statusCode;

        }

 

// Wrapper class for responde

 

}

Thursday, February 18, 2021

How to use getRecord in LWC?

  Using lightning/uiRecordApi we can perform operations as mentioned below without using Apex.

1) Create a record 

2) Get record data

3) Delete a record

4) Get a field value from record

5) Update a record and etc.


In this blog post we will learn How to get record data in lightning/uiRecordApi using getRecord?


Syntax:


import { LightningElement, wire } from 'lwc';

import { getRecord } from 'lightning/uiRecordApi';

 

@wire(getRecord, { recordId: string, fields: string|string[], optionalFields?: string|string[])

propertyOrFunction

 

@wire(getRecord, { recordId: string, layoutTypes: string|string[],

                   modes?: string|string[], optionalFields?: string|string[])

propertyOrFunction


Let's understand with simple example as explained below:

getRecordLWCExample.html

<template >

    <template if:true={contactData}>

     Contact Name : {contactName} <br/>

     Contact Phone  : {contactPhone}

    </template>

</template>


getRecordLWCExample.js

import { LightningElement, api, wire, track } from 'lwc';

import { getRecord } from 'lightning/uiRecordApi';

const FIELDS = ['Contact.Name', 'Contact.Phone'];

export default class GetRecordLWCExample extends LightningElement {

    @api recordId;

    contactData;

    contactName;

    contactPhone;

    @wire(getRecord, { recordId: '$recordId', fields: FIELDS, modes : ['View', 'Edit', 'Create']})

    wiredRecord({ error, data }) {

        if (error) {

             console.log('Received Error');

        } else if (data) {

            console.log('data is'+data);

            

            this.contactData = data;

            this.contactName =   this.contactData.fields.Name.value;

            this.contactPhone =  this.contactData.fields.Phone.value;

            console.log('contact Name is'+this.contactName);

            console.log('contact Phone is'+this.contactPhone);

            

        }

    }

}


getRecordLWCExample.js-meta.xml


<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>50.0</apiVersion>

    <isExposed>true</isExposed>

    <targets>

 

        <target>lightning__RecordPage</target>

 

    </targets>

</LightningComponentBundle>


Add the above component to contact page as shown below,


How to use getRecord in lightning/uiRecordApi?

Saturday, January 16, 2021

How to call an apex method imperatively in lwc

 In this blog post we will learn "How to call an apex method imperatively in lwc".

If we want to control when the method invocation should occurs (for example, in response to clicking a button) than we call the method imperatively. 

When we call a method imperatively, we receive only a single response. 

However with @wire, itdelegates control to the framework and results in a stream of values being provisioned.

Let us understand with a simple example,


getAccountDataImperatively.html

<template>

    <div >

 

        <lightning-input type="text" label="Enter Account Name" value={accName} onchange={handleChange}> </lightning-input>

        <lightning-button variant="base" label="Search Account" title="Search Account" onclick={handleChangeMethod} class="slds-m-left_x-small"></lightning-button>

        <p>Displaying Account Information</p>

 

        <template if:true={accountRecord}>

 

            <template for:each={accountRecord} for:item="item" for:index="index">

 

                <p key={item.Id}>

 

                   Name: {item.Name}

 

                </p>

 

            </template>

 

        </template>

 

        <template if:true={error}>

 

            Some error occured.

 

        </template>

 

    </div>

</template>


getAccountDataImperatively.js

import { LightningElement,track } from 'lwc';

import getAccountRecordMethod from '@salesforce/apex/customAccountController.getAccountRecordMethod';

export default class GetAccountDataImperatively extends LightningElement {

    @track accountRecord;

    @track error;

    @track accName;

 

    handleChange(event){

 

        const userInput = event.target.value;

 

        this.accName= userInput;

 

    }

 

    handleChangeMethod() {

        getAccountRecordMethod({

            accNameParamInApex : this.accName

        })

            .then(result => {

                this.accountRecord = result;

            })

            .catch(error => {

                this.error = error;

            });

    }

   

}



getAccountDataImperatively.js-meta.xml

<?xml version="1.0" encoding="UTF-8"?>

<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">

    <apiVersion>50.0</apiVersion>

    <isExposed>false</isExposed>

</LightningComponentBundle>


customAccountController.cls

public with sharing class customAccountController {

    public customAccountController() {

 

    }

    @AuraEnabled(cacheable=true)

    public static List<Account> getAccountRecordMethod(String accNameParamInApex) {

 

        String accNameKey = '%'+accNameParamInApex+'%';

 

    List<Account> accList=[SELECT Id, Name, Industry

 

        FROM Account

 

        Where name Like: accNameKey];

 

        return accList;

 

    }

}


testingLWCCompApp.app

<aura:application>

<c:getAccountDataImperatively></c:getAccountDataImperatively>

</aura:application>       


Output:

How to call an apex method imperatively in lwc