Blog Categories

Posted by on Aug 23, 2016 in Blog Series, Featured Blogs, Learn Salesforce Lightning with Examples, Tutorials | 31 comments

Learn Salesforce  Lightning with Examples – Part 1 (Create Records using Lightning Components)

Learn Salesforce Lightning with Examples – Part 1 (Create Records using Lightning Components)

Learn Salesforce Lightning with Examples – Part 1 (Create Records using Lightning Components) is the first part of the series – “Learn Salesforce Lightning with Examples“.

Introducing ‘Learn Salesforce Lightning with Examples’ Series

Learn Salesforce Lightning with Examples is the series where We would share the key practical examples and experience with lightning.We are focusing on Lightning Components for now and hope we come up with great stuff later in other lightning features as well.So stay tuned and enjoy our series.

Background & Blog Contributors

Gaurav JainVinay

 

 

 

 

 

Gaurav Jain and I had worked together on lightning projects and We started working from the time when there was not much online material available.We decided to start a blog series to share our learning and experiments with “Lightning Lovers” hoping that they might get benefit from it.Many thanks to Gaurav for helping and being an equal contributor to this blog series.You can connect with Gaurav at twitter and check more about him here.

Pre-Requisites

Here are some pre-requisites for the blog series,Please make sure you implement those so that you are all set for implementing our examples in your developer edition org.

Using Recruiting App

Keeping in mind that our readers might be interested to practice along with us, so We decided to use Recruiting App for all the metadata reference to make sure Users need not create anything extra and just install Recruiting App by Salesforce Labs and you all good to go.You can download the app from AppExchange here.

Set up Domain Name

When you enable My Domain, references and links to Lightning resources are in the format https://<myDomain>.lightning.force.com.Check here –How To Set Up Domain Name.Also for more details why do you want to that,check here for release notes.

Upload BootStrap Static Resource for styling purposes

Download Bootstrap to give some styling from http://getbootstrap.com/.Upload BootStrap css  to static resource.We would refer the path of this css later in our code .

Using Developer Console

For now We are making sure that We use Developer Console for our lightning Components development and tutorials.If not worked yet on it,Check here  for the developer console tutorials.

We would also suggest you to go through this awesome Trailhead module – Lightning Components Basics so that you are familiar with Lightning Components.

Let us jump to our first part now..

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

 

Now you can go to the classic version and see if the record was created :

Create Page 3

You can also download the code from the github repository here.

Hope you enjoyed the blog! Stay tuned and there will be more examples to come ..

31 Comments

  1. Excellent

  2. Excellent vinay, Thank you for creating the series (Type of posts) and sharing.

  3. This blog is having the general information. Got a creative work and this is very different one.We have to develop our creativity mind.This blog helps for this. Thank you for this blog. This is very interesting and useful.

  4. Hi Vinay,

    Thanks for the blog.
    What is the plan for this series?

    How regularly we can check this space for new blogs ?

    • Hi Ashish,
      You can subscribe for the blog and you would be notified when any new blog post is made.
      We are planning one blog every 8-10 days.

  5. Hi Vinay,

    Thanks for the article,

    I have one use case .How to save the record without mentioning attribute tag. Please find the use case details .

    • Fields should be pre-populated based on available info of the logged in user (email address, Surname, First name,Date of birth, present address, town, postcode.

    • The result should generate a case is Salesforce.

    I have done first point ,but am not able to save the record .Please help me out. asap.

  6. Hiii everyone…
    Thank for sharing the informative salesforce blog…

  7. Hi Vinay,

    Superb!!!! nice blog.Thanks for sharing this…

  8. Hi Vinay,

    Superb!!!! nice blog.Please share new posts of salesforce lightning

  9. Hi Vinay,

    Thank you so much for this Lighting blog.

    While saving lighting application getting error “Failed to save undefined: No COMPONENT named markup://c:CreateCandidateRecord found : [markup://c:CandidateRecorddemo]: Source”.

    Request you to please advice

  10. Hi Vinay,
    I have created all the components as per the tutorial. I have created My Domain as well but when I use it, I get an error which says “Lightning components require My Domain. Please contact your system administrator for more information.”. Please let me know what I am missing. My domain is “anant-kamat-dev-ed.my.salesforce.com”. I tried using this “https://anant-kamat-dev-ed.lightning.force.com/c/ManageCandidate.app” but getting the above error. Please help me.

  11. Hi Vinay,
    Thanks for the wonderful tutorial.This is very help full for lightning beginners .
    I’m not getting Proper css through above code.Can you please telll me how to add css to get good look.

  12. Hi Vinay,

    Thanks for the wonderful blog. I have implemented the tutorial as per the steps provided by you. But when my page loads,it just shows up a blank screen. It shows Loading and then a blank screen. Please let me know if I am missing anything. Thanks

  13. Hi Vinay,
    How to create records if we have lookup fields in our form.I’ve created a lightning component, I can save all fields except lookup fields.Please help.
    Anu.

  14. Hi Vinay,
    How to create records if we have lookup fields in our form.I’ve created a lightning component, I can save all fields except lookup fields.Please help.
    Anu.

  15. Code example was clear and precise.

  16. Awesome Vinay…

    Keep posting…..

Post a Reply

Your email address will not be published. Required fields are marked *