banner



Salesforce How To Create A Lightning Component

Lightning Component Bundle

In Salesforce using Lightning components, a developer can build applications and pages by assembling components created by other developers. A component is a user interface developed using HTML, CSS, JavaScript, and other Web-enabled code. This enables you to build apps with sophisticated UIs. Components are the self-contained and reusable units of an app. In this post. I will explain to you the individual components of a lightning component bundle, and show how to create one with an example.

You can use components in many different contexts.

  • Lightning Experience and Salesforce1 Application
  • Lightning Pages
  • Community Builder
  • Lightning Applications
  • Visualforce Pages with Lightning Out
  • Any App with Lightning Out (Beta)

Once created a created lightning component is a bundle of code. The bundle contains all the required resources related to a component like javascript controller, javascript helper, renderer, CSS styles, etc.  A basic lightning component contains the design of a page in Html with some lightning tags. The component uses JavaScript on the client-side and Apex on the server-side. The javascript code is written in the controller, helper, and renderer part of the component bundle.

Resources of a lightning component bundle

    • Component
    • Controller
    • Helper
    • Style
    • Documentation
    • Renderer
    • Design
    • SVG

Component

Contains the Html like code for a component along with some lightning tags. Whenever you start building your component code, the root tag for the component will be <aura: component> tag and you can design the component using other available aura tags.

Controller

Contains the javascript code for your component to call the action events declared in the lightning component. It calls the doInit method that runs before your component Html content is loaded, doInit is not required in all components.

Helper

Helper contains the javascript code for your component just like your controller but the purpose of the helper is to segregate the calls to the server. The methods defined inside the helper can be called from the controller and renderer, hence making it more reusable. You write those methods in the helper which are basically reusable and may be required to be called multiple times. So it is best practice to separate your client-side javascript from your server calls as the server calls run asynchronously.

Helper functions are local to a component, improve code reuse, and move the heavy lifting of JavaScript logic away from the client-side controller, wherever possible.

    1. Use Controllers to listen to user events and other events like components, application events. But delegate business logic to the helper.
    2. Do similar delegation in all Renderer functions (render, re-render, and so on).
    3.  Anytime you need to call one controller function from another controller function, move that logic to Helper.

Style

This style resource contains the custom style classes that you are going to use in your component.

Renderer

Contains code that you want to execute before or after rendering of your component elements. You can make calls to your helper methods also in the renderer. There are four types of rendering behavior i.e. Render, AfterRender, Rerender, and Unrender.

Render: Render function is called when the component is being initialized. This function returns an array of DOM nodes. Use render function to modify DOM or to modify component markup.

AfterRender: AfterRender function is called by the framework after the render function. AfterRender function allows you to further change an already rendered component. The afterRender function enables you to interact with the DOM tree after the framework's rendering service has inserted DOM elements.

Rerender: Rerender function will be called when a component's value changes due to user action like a button click or some other event like component/application event. Rerender function updates component upon re-rendering of the component.

Unrender: Framework fires an unrender event when a component is deleted. The base unrender function deletes all the DOM nodes rendered by a component's render function. It is called by the framework when a component is being destroyed. Customize this behavior by overriding unrender in your component's renderer. This can be useful when you are working with third-party libraries that are not native to the framework.

Design

Design resource is used to create attributes that you want to use at the design time i.e. while using the Lightning App builder tool. When you are using your components on a record detail page you have the option to set some of the attributes for your components to customize their behavior. These attributes are specified in the design component.

SVG

SVG stands for Scalable Vector Graphics. It is a custom icon resource for components used in Lightning App Builder or Community Builder and if we want to customize this icon to some other icon, we need to create an SVG for our lightning component. so that, when viewing the component at design time(in Lightning App Builder) the component appears with the icon specified in the SVG component.

Create a Lightning component

Let us build a simple component to create a contact record using all resources from lightning component bundles.

Steps to create a lightning component

1. Open the Developer Console from Lightning Experience:

  • Click the quick access menu ( ) > Click Developer Console.

2. In the Developer Console, select File > New > Lightning Component.

3. Enter the component name (say QuickContact) and description (optional).

4. Click on submit.

5. QuickContact.cmp workspace will be created with the root tag <aura: component>. Now copy and paste the below given QuickContact.cmp code and save.

QuickContact.cmp

<aura:component implements="force:appHostable,flexipage:availableForAllPageTypes,force:lightningQuickAction,force:hasRecordId" access="global" controller="ContactListController">
    <aura:attribute name="AccountId" type="String" />
    <aura:attribute name="backgroundColor" type="String" default="#000000″/>
    <aura:attribute name="textFontSize" type="Integer" default="18″ />
    <aura:attribute name="textColor" type="String" default="#e81717″ />
    <aura:dependency resource="markup://force:editRecord" type="EVENT" />
    <aura:registerEvent name="quickContact" type="c:QuickContactEvent"/>
    <lightning:navigation aura:id="navService"/>
    <aura:attribute name="createContact" type="Contact" default="{
                                                                 sobjectName : 'Contact',
                                                                 FirstName: ",
                                                                 LastName : ",
                                                                 Email: ",
                                                                 Phone :" }" />
    <div style="{!'padding:' + v.boxPadding +'px; background-color:' + v.backgroundColor}">
        <p style="{!'font-size:' + v.textFontSize + 'px; color:' + v.textColor}">
            <div class="slds-p-around_x-small">
                <lightning:input type="text" value ="{!v.createContact.FirstName}" label="First Name" required="true" />
                <lightning:input type="text" value ="{!v.createContact.LastName}" label="Last Name" required="true" />
                <lightning:input type="email" value="{!v.createContact.Email}" label="Email"/>
                <lightning:input type="phone" value="{!v.createContact.Phone}" label="Phone"/>
                <lightning:button label = "Create Contact" class = "btn" onclick = "{!c.doSave}" />
            </div> </p> </div>
</aura:component>

6. For the above-created component create a new apex class in the Developer Console by clicking File > New > Apex Class, then copy and paste the below ContactListController.apxc code and save.

ContactListController.apxc

public class ContactListController {
    @AuraEnabled
    public static Contact createContact (Contact con, Id AccountId){
        con.AccountId = AccountId;
        insert con;
        system.debug('The inserted Id is' + con.Id);
        return con;
    }

7. In the right tab panel, click on the controller or Ctrl + Shift + 2 to open the controller tab and paste the below QuickContactController.js code and save.

QuickContactController.js

({
    doSave : function(component, event, helper) {
        debugger
        var action = component.get('c.createContact');
        var accid = component.get('v.recordId');
        var contc = component.get('v.createContact');
        if(contc.FirstName=== null||contc.FirstName ===" ||contc.FirstName === undefined){
            return;
        }
        action.setParams({
            con : component.get('v.createContact'),
            AccountId : component.get('v.AccountId')
        });
        action.setCallback(this, function(response) {
            var state = response.getState();
            if(state === 'SUCCESS' || State === 'DRAFT' ){
                var responseValue = response.getReturnValue();
                var toastEvent = $A.get("e.force:showToast");
                $A.get('e.force:refreshView').fire();
                helper.toastMsg( 'Success', 'This is a success message');
            }else if(state === 'INCOMPLETE' ){
            }else if(state === 'ERROR' ){
            }
        }, 'ALL');
        $A.enqueueAction(action);
    }
})

8. In the right tab panel, click on the helper or Ctrl + Shift + 3 to open the helper tab and paste the below QuickContactHelper.js code and save.

QuickContactHelper.js

({

    toastMsg : function( strType, strMessage ) {
var showToast = $A.get( "e.force:showToast" );
showToast.setParams({
message : strMessage,
type : strType,
duration : 5000,
mode : 'dismissible'
        });
showToast.fire();
    }
})

9. In the right tab panel, click on the style or Ctrl + Shift + 4 to open the style tab and paste the below QuickContact.css code and save.

QuickContact.css

.THIS .btn {

    background: linear-gradient(90deg, #be2edd, #5f27cd);
    color: #fff;
    font-size: 16px;
    padding: 10px 45px;
    border: none;
    border-radius: 25px;
    outline: none;
    cursor: pointer;
    left: 50%;
}
.THIS .btn:hover {
    background: linear-gradient(90deg, #808000, #806000);
}

10. In the right tab panel, click on the documentation or Ctrl + Shift + 5 to open the documentation tab and paste the below QuickContact.css code and save.

QuickContact.auradoc

<aura:documentation>

<aura:description>
<p>An <code>c:QuickContact</code> component is created to insert a contact to a corresponding account.</p>
    </aura:description>
<aura:example name="QuickContact" ref="c:QuickContact" label="Quick Contact">
<p>This example shows a simple setup of <code>QuickContact</code>.</p>
</aura:example>
</aura:documentation>

11. In the right tab panel, click on the renderer or Ctrl + Shift + 6 to open the renderer tab and paste the below QuickContactRenderer.js code and save.

QuickContactRenderer.js

({
    // Your renderer method overrides go here
    render:function(component,helper) {
// Call Base render method
var a = this.superRender();
// custom rendering
console.log("This text is from render function which gets executed when component is initiated");
return a;
    },
    afterRender:function(component,helper) {
//Call Base afterrender method
this.superAfterRender();
// Interact with Dom elements
console.log("This text should come after render() is over");
console.log("This text is from afterRender function");
    },
    rerender:function(component,helper) {
//call Base rerender method
this.superRerender();
//custom rerendering
console.log("This text is from rerender function…which gets called whenever and data change occurs");
    }
})

12. In the right tab panel, click on the design or Ctrl + Shift + 7 to open the design tab and paste the below QuickContact.design code and save.

QuickContact.design

<design:component>

    <design:attribute name="backgroundColor" label="Background Color" description="Enter Background Color"/>
     <design:attribute name="textFontSize" label="Font Size" description="Enter font size without 'px' [i.e 15]"/>
      <design:attribute name="textColor" label="Font Color" description="Enter font Color" />
</design:component>

13. In the right tab panel click on the svg or Ctrl + Shift + 8 to open the svg tab and paste the below QuickContact.svg code and save.

QuickContact.svg

<?xml version="1.0″ encoding="UTF-8″ standalone="no"?>
<svg width="120px" height="120px" viewBox="0 0 120 120″ version="1.1″ xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g stroke="none" stroke-width="1″ fill="none" fill-rule="evenodd">
<path d="M120,108 C120,114.6 114.6,120 108,120 L12,120 C5.4,120 0,114.6 0,108 L0,12 C0,5.4 5.4,0 12,0 L108,0 C114.6,0 120,5.4 120,12 L120,108 L120,108 Z" id="Shape" fill="#BFFF00″/>
</g>
</svg>

14. Now navigate to the contact object record detail page and click the quick access menu >  Edit Page, The lightning app builder page with a list of available components opens.

Lightning App Builder

15. Scroll down to select the created custom components, click and drag the component into the page layout. The user can customize the component design by using the design component on the right side of the lightning app builder page. Click on the save button to save the changes made to the lightning app builder page.

Design component

Output

Output from the component

That's it! Now the QuickComponent can insert contacts as seen in the above image.

Hope this article would've helped you in understanding how to create and edit a components UI based on the user requirement using the lightning component bundle

Please check out other salesforce.com blogs from our team at  http://bestirtech.com/blog/category/salesforce.com/ and share your comments.

Post Views: 1,898

Salesforce How To Create A Lightning Component

Source: http://bestirtech.com/blog/2020/12/lightning-component-bundle-in-salesforce/

Posted by: hassourprive.blogspot.com

0 Response to "Salesforce How To Create A Lightning Component"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel