Friday, March 16, 2018

Creating a Custom Lightning Component to create record

Business Case:

Adam is working as a Senior Application Developer in Universal Containers. Company wants to move their traditional (classic version )recruitment app to lighting. Adam needs to do a Proof of Concept by building a custom lighting component for creating the Candidate’s record into Salesforce.

Solution:

Adam decided to create a lightning component which would display a form with a ‘Create’ button and on click of that button ,records get saved into the salesforce system.
Before getting started,Adam makes sure that he doesn’t miss any pre-requisites mentioned above.Below are the steps,Adam takes for the creating the solution after completing the pre-requisites.
  1. Finishing all the pre-requisites.
  2. Creating Lightning Component.
  3. Creating Lightning Controller for the component.
  4. Creating Apex Class and create method.
  5. Creating an Application to host the component.
  6. Test the Application

Create Lightning Component

First thing which We are going to do is creating a lightning component so that from here,We get an idea where and what to do next.
Go to setup->Developer console, At Developer console Click on New to create lightning component and paste the below code :
<!--
DISCLAIMER:
THIS CODE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-->
<!--
          ** Component Details***
         Name: CreateCandidateRecord
         Type: Lightning Component 
         Purpose: Component to create records
-->


<aura:component controller="CreateCandidateRecord" 
    implements="force:appHostable,flexipage:availableForAllPageTypes,flexipage:availableForRecordHome,
       force:hasRecordId,forceCommunity:availableForAllPageTypes" 
    access="global" >
    
    <!-- Include Static Resource-->
    <ltng:require styles="/resource/bootstrap/css/bootstrap.min.css" 
      scripts="/resource/bootstrap/js/jquery.js,/resource/bootstrap/js/bootstrap.min.js"/>
    
    <!-- Define Attribute-->
    <aura:attribute name="candidate" type="Candidate__c" default="{'sobjectType': 'Candidate__c',
                         'First_Name__c': '',
                         'Last_Name__c': '',
                         'Email__c': '', 
                         'SSN__c': ''
                       }"/>
    <div class="container-fluid">
        <h3>Please Enter The Candidate Information</h3>
        <div class="form-group">
            <label>First Name</label>
            <ui:inputText class="form-control" value="{!v.candidate.First_Name__c}"/>
        </div>
        <div class="form-group">
            <label>Last Name</label>
            <ui:inputText class="form-control" value="{!v.candidate.Last_Name__c}"/>
        </div>
        <div class="form-group">
            <label>Email Address</label>
            <ui:inputText class="form-control" value="{!v.candidate.Email__c}"/>
        </div>
        <div class="form-group">
            <label>SSN</label>
            <ui:inputText class="form-control" value="{!v.candidate.SSN__c}"/>
        </div>
    </div>
    <div class="col-md-4 text-center">
        <ui:button class="btn btn-default" press="{!c.create}">Create</ui:button>
  </div>
</aura:component>
  

Create Controller for the Lightning Component

Now,since you have created a component,you would like to handle the logic at lightning level first before moving to apex side,so you need to create component controller by clicking on controller in right panel as mentioned in below image and copy paste the code below.
Dev Console
/*
 * DISCLAIMER:
THIS CODE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, 
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * */
/************************************************************
 Lightning Controller  Details
 Name: CreateCandidateRecordController.js
 Type: Lightning Controller 
 Purpose: Controller for  lightning component 
    CreateCandidateRecordController.cmp
 ***********************************************************/
({
 create : function(component, event, helper) {
  console.log('Create record');
        
        //getting the candidate information
        var candidate = component.get("v.candidate");
        
        //Validation
        if($A.util.isEmpty(candidate.First_Name__c) || $A.util.isUndefined(candidate.First_Name__c)){
            alert('First Name is Required');
            return;
        }            
        if($A.util.isEmpty(candidate.Last_Name__c) || $A.util.isUndefined(candidate.Last_Name__c)){
            alert('Last Name is Rqquired');
            return;
        }
        if($A.util.isEmpty(candidate.Email__c) || $A.util.isUndefined(candidate.Email__c)){
            alert('Email is Required');
            return;
        }
        if($A.util.isEmpty(candidate.SSN__c) || $A.util.isUndefined(candidate.SSN__c)){
            alert('SSN is Required');
            return;
        }
        //Calling the Apex Function
        var action = component.get("c.createRecord");
        
        //Setting the Apex Parameter
        action.setParams({
            candidate : candidate
        });
        
        //Setting the Callback
        action.setCallback(this,function(a){
            //get the response state
            var state = a.getState();
            
            //check if result is successfull
            if(state == "SUCCESS"){
                //Reset Form
                var newCandidate = {'sobjectType': 'Candidate__c',
                                    'First_Name__c': '',
                                    'Last_Name__c': '',
                                    'Email__c': '', 
                                    'SSN__c': ''
                                   };
                //resetting the Values in the form
                component.set("v.candidate",newCandidate);
                alert('Record is Created Successfully');
            } else if(state == "ERROR"){
                alert('Error in calling server side action');
            }
        });
        
  //adds the server-side action to the queue        
        $A.enqueueAction(action);

 }
})

Create Apex class and define method to create the candidate record

Now We have written logic in such a way that Component will call lightning controller and lightning controller will invoke Method written in apex class.So copy paste the below apex class in your org.
/************************************************************
 
 Name: CreateCandidateRecord
 Type: Apex Class  
 Purpose: Apex Class  for  lightning component 
    CreateCandidateRecordController.cmp
 ***********************************************************/
public with sharing class CreateCandidateRecord {

    /**
   * Create a new candidate Record
   *
   * @param Candidate__c candidate  candidate record to be inserted
   * 
   */
    @AuraEnabled
    public static void createRecord (Candidate__c candidate){
        
        try{
            System.debug('CreateCandidateRecord::createRecord::candidate'+candidate);
            
            if(candidate != null){
                insert candidate;
            }
            
        } catch (Exception ex){
            
        }
        
    }    
}

Create lightning application to host the component in the App

You need to host your component somewhere where you can show it(We would talk about various ways to host the components in later posts in series).So here we have created a Lightning App for the hosting.Create an application from Developer Console->New Lightning Application and then copy paste the below code and you are all set to test this Application.
<!--
          ** Application Details***
         Name: ManageCandidate
         Type: Lightning Application 
         Purpose: Application to host the lightning components
-->

<aura:application >
    <aura:dependency resource="c:CreateCandidateRecord" />
    <c:CreateCandidateRecord />
</aura:application>

Test the Application

Now since We are done with the codes,lets test the application.So in our case,We need to try with the URL format :
https://{Domain Name}.lightning.force.com/c/{App Name}.app
and then you would get a similar page like this :
Lightning App Screen
Fill the details and hit the “Create” button.Also make sure you fill all the details as you might get errors to fill them since we have added validations to make these fields required.
Create Page 2

No comments:

Post a Comment