Sunday, December 17, 2017

Crate a lightning component to insert record.

Scenario: Suppose we have a Student object with 2 custom field Roll No and Class. Now our aim is to create a lightning component to insert Student record and to access this component we will create a custom "Lightning Component Tab".

Solution: To solve the above scenario please follow the below steps,

1. Create a Student Object with below fields,

  • Standard field "Student Name" will automatically created.
  • Create 2 custom fields,
  1. Roll No        Roll_No__c Number(18, 0)
  2. Class        Class__c         Text(10)
2. Create a lightning component named as "NewStudent" (To create lightning component please check my previous post, where I mentioned detail screen shots).
In the component header implements="force:appHostable" . This is because we want to create a "Lightning Component Tab" for this component (NewStudent). Now the component is look like this,








3. Now in our component we have to create 3 input fields (Student Name, Roll No and Class) and one button (Save).
[Note 1: We can make different slds styling as per our requirement. For this example I am using "lightning:card"].

[NOTE 2 : Before copy paste below component's code base just create an apex class named as "NewStudentCtrl", because this component has a reference of this apex class. Code base is described later.]



<!-- ######## NewStudent.cmp ###### -->

<aura:component implements="force:appHostable"
                 controller="NewStudentCtrl">
    <!-- Attribute declaration -->
    <aura:attribute name="studentObj" type="Student__c" default="{ 'sobjectType': 'Student__c'}"/>
    
    <div class="slds-grid">
        <lightning:card title="New Student" footer="Click on Save button to create new Student.">
            <!-- Save button -->
            <aura:set attribute="actions">
                <lightning:button aura:id="saveId"
                                  label="Save"   
                                  onclick="{!c.doSave}"/>
            </aura:set>
            <!--/ Save button -->
            
            <!-- Body -->
            <p class="slds-p-horizontal_small">
                <lightning:input aura:id="stdName"
                                 label="Student Name"
                                 type="String"
                                 required="true"
                                 value="{!v.studentObj.Name}"/>
                <lightning:input aura:id="stdClass"
                                 label="Class"
                                 type="String"
                                 value="{!v.studentObj.Class__c}"/>
                <lightning:input aura:id="stdRoll"
                                 label="Roll No"
                                 type="Number"
                                 value="{!v.studentObj.Roll_No__c}"/>
            </p>
            <!--/ Body -->
        </lightning:card>
    </div>
    
</aura:component>

4.  Now click on controller and copy-paste the below code same for our example.


({
 doSave : function(component, event, helper) {
  /** Server side controller calling logic. **/
        
        //Calling server side controller's saveStudent() method.
        var action = component.get("c.saveStudent");
        //Set method parameter of saveStudent() method.
        action.setParams({"student": component.get("v.studentObj")});
        
        action.setCallback(this, function(response){
            //<response.getState()> return response status as SUCCESS/ERROR/INCOMPLETE etc.
            var state = response.getState();
            //If response from server side is <SUCCESS>, then we will display a success message.
            if (state === "SUCCESS"){
                //Success message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "Success!",
                    "message": "Student record has been inserted successfully."
                });
                toastEvent.fire();
            }else if (state === "INCOMPLETE") {
                //Offline message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "OFFLINE!",
                    "message": "You are in offline."
                });
                toastEvent.fire();
            }else if (state === "ERROR") {
                //Error message display logic.
                var errors = response.getError();
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "ERROR!",
                    "message": errors[0].message
                });
                toastEvent.fire();
            }else {
                //Unknown message display logic.
                var toastEvent = $A.get("e.force:showToast");
                toastEvent.setParams({
                    "title": "UNKOWN!",
                    "message": "Unknown error."
                });
                toastEvent.fire();
            }
        });
        
        $A.enqueueAction(action);
 }
})



5. Now copy-paste server side controller class, which will responsible for inserting student record.


/**
  * @name:        NewStudentCtrl      
  * @date:        14 Dec 2017
  * @description: This is the server side controller class for <NewStudent> lightning component.
  *          Server side insertion will be perform here.
***/
public with sharing class NewStudentCtrl{
    /**
 * @name:        saveStudent      
 * @date:        14 Dec 2017
 * @description: This method is responsible to create student record. As this method is calling from
 *         client side lighthing component, so this should be annoted with <@AuraEnabled>.
 ***/
    @AuraEnabled
    public static void saveStudent(Student__c student){
        INSERT student;
    }
}



6. Once the above activities have been done, we have to create a custom "Lightning Component Tab" to execute the component (NewStudent).
























7. Now time to test the component. Click on "New Student" tab and it will open the below screen.




















8. Enter values as per screen and click on save button and it will insert a student record and if operation done successfully,then it will shown a success message as popup.













LWC to LWC Communication using Lightning Messaging Service (Part - 2)

In my previous post ( previous post link ) we have learn how to create a Lightning Messaging Service with 6 steps and today we will use the ...