Sunday, March 14, 2021

How to use getObjectInfo in Lightning Web Component?

 In this blog post we will learn how to use getObjectInfo in Lightning Web Component.


Let us take a simple example to understand the use of getObjectInfo in Lightning Web Component.


objectInfoComp.html

<template>

  <p>Object Info Component</p> 

</template>

objectInfoComp.js

import { LightningElement, wire } from 'lwc';

import { getObjectInfo } from 'lightning/uiObjectInfoApi';

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

export default class ObjectInfoComp extends LightningElement {

    @wire(getObjectInfo, { objectApiName: ACCOUNT_OBJECT })

    wiredData({data, error}){

       if(data){

         console.log('Object INFO:', data);

       }

       if(error){

         console.log('Some Error Occured');

       }

    }

 

}

objectInfoComp.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>

Now, Add the component on account record lightning page as shown below,

getObjectInfo in Lightning Web Component

Open the console and we will be able to see all different information related to the object as shown below.


How to use getObjectInfo in Lightning Web Component?

Tuesday, March 9, 2021

What are data types in Javascript?

 A) Values in Javascript will have a type.


B) There are 8 basic data types in Javascript.


1) String


let name = 'Test';  


String in Javscript is surrounded by quotes. 

Quotes can single, double quotes.


2) Number


let n = 10;  // Number


3) Boolean


let checkName =  true;

let checkData = false;


4) "null" 


It contains only null value. 

In Javascript, null is not a reference to a non existing object or null pointer. 

It just represents empty or unknown value.


let a= null;


5) "undefined"


It also represent special type, here the variable is declared but not assigned any value as shown below,


let a;


6) bigint


Used to store integers value of arbitrary length.


bigint value is created by appending n to the end of an integer.


const = 11111111112222222223333333333344444444n;


7) object


a) object are used to store collections of data and more complex entities.


b) objects can be created using {...} with optional list of properties, a property is "key": "value" pair.


c) Creating an empty object,


let studentDetail = {};

let steudentDetail = new Object();



d) Creating an object with properties,


let studentDetail = {

"name": "Test",

"rollNo": 1,

"Full Name": "Test User"


};


e) To access the property values use dot notation or array notation in case of space in key name as shown below,


studentDetail.name  // dot notation


To access full name use array notation as it has space.


studentDetail[Full Name]   // array notation


f) Adding a value to property,


studentDetail.department = 'Computer Science';


g) We may add comma to last property as shown below.


let studentDetail = {

name: "Test",

rollNo: 1,

};


h) To access the keys use,


Object.keys(studentDetail)


i) Use JSON.stringify to convert object to string


var jsonStrng= JSON.stringify(studentDetail);


console.log(jsonStrng);


"{"name":"Test","rollNo":1,"Full Name":"Test User"}"


j) Use JSON.parse to convert string to object


Object = JSON.parse(jsonStrng);


{name: "Test", rollNo: 1, Full Name: "Test User"}



k) The below are also different kinds of object in Javascript,


Array

Date

Error


8) symbol

What are variables and constants in Javascript?

 (A) Variables:


1) Variable are used to store data values. 


2) Variable name contains only letters, digits or the symbol $ and _.


3) Variable name must begins with letter, $ and _ and not with digits.


4) To create variable we use let as shown below,


let name = 'Test';


In older scripts keyword "var" is used.


var name = 'Test';


5) We can also declare a variable as shown below without using let, this was mainly possible during old times and this still works unless we don't put "use strict" in our script.


Ex:


num = 10;  // will work


Ex:


"use strict";


num = 10; // error: num is not defined



(B) Constants:


1) Constants are unchanging variables.


2) Declare a constant with const keyword.


3) If we are sure that variable will never change its values use const keyword before variable.



Ex:


const tDay = '01.01.2000';



Summary:


1) let is a modern variable declaration.


2) var is old school variable declaration.


3) const is similar to let but value of variable can't be changed.

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;

        }

        

      }

   }