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);
    }
})