Monday, September 16, 2019

Lightning Components and Custom Apex Classes attribute type with Save Records

Apex Class
Information is encapsulated in the RecordCounts custom Apex class, which also doubles as the Apex controller for the component, providing the GetRecordCounts method to retrieve the information. Note that the methods and attributes for use client-side have the AuraEnabled annotation:

public class RecordCounts {
    @AuraEnabled
    public Integer numAccounts {get; set;}
     
    @AuraEnabled
    public Integer numContacts {get; set;}
     
    @AuraEnabled
    public Integer numOpportunities {get; set;}
       @AuraEnabled
    public String Carname{get; set;}
       @AuraEnabled
    public String Carmilage{get; set;}
    @AuraEnabled
    public static RecordCounts GetRecordCounts()
    {
        RecordCounts result=new RecordCounts();
        result.numAccounts=[select count() from Account];
        result.numContacts=[select count() from Contact];
        result.numOpportunities=[select count() from Opportunity];
        // if you have Record Id and then pass it as param and can get Record details on page load               with Edit mode 
        car__c objcar=[Select id,name ,Mileage__c from car__C limit1][0];
        result.Carname=objcar.name;
        result.Carname=objcar.Mileage__c ;
        return result;
    }
     @AuraEnabled
     public static String saveCarRequest(string objReqStr) //
    {
        String s= 'a';
        RecordCounts objReq = (RecordCounts)JSON.deserialize(objReqStr, RecordCounts.class);
        car__c objcar=new car__C();
        objcar.name=objReq.Carname;
         objcar.Mileage__c=objReq.Carmilage;
         insert objcar;
        return s;
    }

}

Lighiting Component 

   <!--RecordCount-->

<aura:component controller="RecordCounts">
    <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
    <aura:attribute type="RecordCounts" name="counts" />
    Number of accounts = {!v.counts.numAccounts}
    
    Number of contacts = {!v.counts.numContacts}
    
    Number of opportunities = {!v.counts.numOpportunities}
    <ui:inputText aura:id="counts" maxlength="40" label="Car Name"
                  value="{!v.counts.Carname}" required="true"   />
    <ui:inputText aura:id="counts" maxlength="40" label="Car Milage"
                  value="{!v.counts.Carmilage}" required="true"   />
    
    <br></br>
    <div class="slds-grid slds-gutters">
        <lightning:button  label="Save" variant="brand"  onclick="{!c.handleSaveProductRecord}"/>
        <lightning:button  label="Submit" variant="brand" />
    </div>
</aura:component>

The lightning component is very straightforward - it defines that the Apex controller is ‘RecordCounts’, provides an attribute to store the retrieved record count instance in and has markup to output the value as well as some more input fields also.  The information is retrieved from the server via the doInit event handler, which will be invoked when the component is initialised but before it is rendered. 




Note that the type of the ‘counts’  attribute is defined as the name of the custom apex class - RecordCounts. Note also that I can simply access properties from the Apex class using the JavaScript object dot notation, as the record instance has been converted to a Javascript object representation.

Contoller .js
 Lightning Components best practice, the component controller simply delegates to a helper for the init event callback handler:

({ doInit : function(component, event, helper) { helper.doInit(component, event); }, handleSaveProductRecord: function(component, event, helper) { var reObj=component.get('v.counts'); var action = component.get("c.saveCarRequest"); var jsonOppty = JSON.stringify(reObj); action.setParams({ "objReqStr": jsonOppty }); action.setCallback(this, function(response) { var state = response.getState(); if (state === "SUCCESS") { alert('hello'); } else { } }); $A.enqueueAction(action); }, })

Helper.js
while the helper executes the server side method and sets the Javascript object representation of the Apex class instance into the ‘counts’ attribute upon success without any intervention from me to process the result or translate it to something that the component can use directly, as this is all handled by the framework:

({
doInit : function(cmp, ev) {
        var action = cmp.get("c.GetRecordCounts");
        action.setCallback(this, function(response) {
            var state = response.getState();
            if (state === "SUCCESS") {
                cmp.set('v.counts', response.getReturnValue());
            }
            else if (state === "ERROR") {
                alert('Error : ' + JSON.stringify(errors));
            }
        });
        $A.enqueueAction(action);
    }
})

Friday, September 6, 2019

How To Use jQuery DataTable Plugin In Salesforce Lightning Component


How To Use jQuery DataTable Plugin In Salesforce Lightning Component 

jQuery DataTables is a very powerful plugin for creating table with advanced interaction controls. It provides searching, sorting, pagination  and many more cool features without any configuration. In this post we are going to learn how we can use this jQuery datatable in salesforce lightning components.
So in this sample post, we will fetch the opportunity object records from server and after that display those records using jQuery data table.
Step 1 : Download & Upload jQuery library and  jQuery data table plugin, in static resource.
In order to use data table jQuery plugin, you must include the jQuery, javaScript and CSS file on your Lightning Component via static resources.
Download Data Table jQuery Plugin
Download jQuery library [version 2.2.4 Recommended]
  • jQuery version 2.2.4 is NOT included within the dataTable plugin zip file – you must download it.
  • Go to below link for download JQuery 2.2.4 minified version. (2.2.4 Recommendation)
  • https://code.jquery.com/jquery-2.2.4.min.js
  • Save the JS file on your computer.
Step 2 : Upload Data Table zip file + jQuery js file as a static resources in your Salesforce org.
Static resource is a file or collection of files that is stored on Salesforce. Once your Data Table zip file and jQuery2.2.4 JS file  is added as a static resource, it can be referenced by any of your lightning component.
  • After successfully download both files (DataTables-1.10.16.zip + jQuery js file) now, we can upload these as a static resources.
  • For upload zip file, from Setup >> Develop >> Static Resources >> New.
  • In the Name field, enter the name which is use in lightning component.
  • Click Choose File or Browse, and select dataTable zip file which we downloaded before.
  • In the Cache Control drop-down list, select Public.
  • Click on the Save button.
Follow same steps to upload both files.
Data Table Zip file upload…
 
jQuery 2.2.4 JS file upload
Step 3 : Use jQuery Data Table on salesforce lightning component.
Step 4 : Create Apex Controller 
From developer console >> file >> new >> Apex Class 
jQueryDataTableCtrl.apxc
Step 5 : Create Lightning Component
From developer console >> file >> new >> Lightning Component 
dataTableDemo.cmp
                    Type
                    Stage
                    Amount
                    Close Date
                
            
            
                items="{!v.lstOpp}" var="acc">
                    
                        {!acc.Name}
                        {!acc.Type}
                        {!acc.StageName}
                        {!acc.Amount}
                        {!acc.CloseDate}
                    
                
  
            
        
    
 
 
  • By the ltng:require tag in lightning component we can load external CSS and JavaScript libraries after we upload them as static resources.
dataTableDemoController.js
From developer console >> file >> new >> Lightning Application
demo.app [Lightning Application]