Sunday, 25 March 2018

lightning:radioGroup values preparation from Apex Class

Hi ,

Here in the following i am preparing the values from Apex class for lightning:radioGroup.

Lightniong:radiogroup:
-----------------------------

Apex Controller:
-------------------
public class LightningRadioGroup {
   @Auraenabled
    public static Map<string,String> retrieveValues(){
        Map<String,String> dummyValuesMap = new Map<String,String>();
        dummyValuesMap.put('balaji','balaji');
        dummyValuesMap.put('Sree Valli','Sree Valli');
        return dummyValuesMap;
    }
     @Auraenabled
    public static String retrieValuesinJSON(){
        JSONGenerator gen = JSON.createGenerator(true);
        gen.writeStartArray();
        gen.writeStartObject();
            gen.writeStringField('class','optionClass');
            gen.writeStringField('label','Balaji');
            gen.writeStringField('value','Balaji');
        gen.writeEndObject();
         gen.writeStartObject();
            gen.writeStringField('class','optionClass');
            gen.writeStringField('label','Alivelimanga');
            gen.writeStringField('value','Alivelimanga');
        gen.writeEndObject();
        gen.writeEndArray();
        String jsonString= gen.getAsString();
        System.debug('jsonString:'+jsonString);
        return jsonString;
    }
}
---------------
RadioGroup.cmp: (preparation of values using Map)

<aura:component controller="LightningRadioGroup">
    <aura:handler name="init" value="{!this}" action="{!c.usingMap}"/>
    <aura:attribute name="optionsList" type="List" /> 
    <aura:attribute name="value" type="String" default="option1"/>
    <div class="slds-form slds-form_stacked">
        <h1>Lightning Radio Group Example</h1>
    <lightning:radioGroup aura:id="mygroup"
                name="radioButtonGroup"
                label="Radio Button Group Usin Map"
                options="{!v.optionsList}"
                value="{!v.value}"       
                required="true" />
   
    </div>
</aura:component>

RadioGroupController.js:
----------------------------
({
usingMap : function(component, event, helper) {       
var action = component.get("c.retrieveValues");
        action.setCallback(this,function(response){
            var values = [];
            var result = response.getReturnValue();
            for(var key in result){
                values.push({
                    class:'optionClass',
                    label:key,
                    value:result[key]});     
            }
            component.set("v.optionsList",values);
        });
        $A.enqueueAction(action);
}
})



RadioGroupusinJSON.cmp: (Displaying values using JSON string)

<aura:component controller="LightningRadioGroup">
    <aura:handler name="init" value="{!this}" action="{!c.usingJSON}"/>
    <aura:attribute name="optionsJSON" type="String" /> 
    <aura:attribute name="value" type="String" default="option1"/>
    <div class="slds-form slds-form_stacked">
    <lightning:radioGroup aura:id="mygroup"
                name="radioButtonGroup"
                label="Radio Button Group Usin JSON"
                options="{!v.optionsJSON}"
                value="{!v.value}"       
                required="true" />
   
    </div>
</aura:component>

RadioGroupusinJSONController.js:
({
usingJSON : function(component, event, helper) {       
var action = component.get("c.retrieValuesinJSON");
        action.setCallback(this,function(response){         
            var result = response.getReturnValue();
            component.set("v.optionsJSON",JSON.parse(result));         
        });
        $A.enqueueAction(action);
}
})


Output:
---------



References:
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_lightning_radioGroup.htm

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_ui_inputRadio.htm

Lightning Picklist Helper and Component Event Example

Hi ,

I am going to explain a reusable component for picklist . We can use it in any component for generating picklist.

It has following parameters to set dynamically.
objectName -- For which object we have to generate piclist
FieldName -- It is Picklist Field API name
FieldLabel -- Label of the Picklist field
MultiSelect -- We can setup picklist as muliselect or single select
SelectedValue -- We can set up default value

We have to create an event to pass selected value from PicklistHelper Component. Here

we are using component event.

PickListEvent.evt:

<aura:event type="Component" description="Event fire when some one selects a value in picklist" >
    <aura:attribute name="SelectedValue" type="string" description="The result of the Selection"/>

</aura:event>


PicklistHelper.cmp:

<aura:component controller="PicklstHelper">
  <aura:registerEvent name="PicklistSelected" type="c:PickListEvt"/>
   <aura:handler name="init" value="{!this}" action="{!c.doInit}"/>
   <aura:attribute name="objectName" type="String"/>
    <aura:attribute name="FieldName" type="String" />
    <aura:attribute name="FieldLabel" type="String" default="PickLIst"/>
    <aura:attribute name="MultiSelect" type="Boolean" default="false" />
    <aura:attribute name="SelectedValue" type="String" default="" />
   <div class="slds-form-element">
      <label class="slds-form-element__label" for="select-01">{!v.FieldLabel}</label>
      <div>
         <ui:inputSelect aura:id="PickListId" multiple="{!v.MultiSelect}" class="slds-select"  change="{!c.onPicklistChange}"/>
      </div>
   </div>

</aura:component>

PickListHelperController.JS:
---------------------
({
    doInit: function(component, event, helper) {        
        helper.fetchPickListVal(component, 'PickListId', component.get("v.SelectedValue"));
    },
onPicklistChange : function(component, event, helper) {
// get the value of select option
        var SelectPicklist = component.getEvent("PicklistSelected");
        SelectPicklist.setParams({
            SelectedValue: event.getSource().get("v.value")
        }).fire();      
}
})

PickListHelperHelper.JS:
---------------------
({
fetchPickListVal: function(component, elementId, selectedVal) {
        var action = component.get("c.getselectOptions");
        action.setParams({
            "objectName": component.get("v.objectName"),
            "fieldName": component.get("v.FieldName")
        });
        var opts = [];
        action.setCallback(this, function(response) {
            if (response.getState() == "SUCCESS") {
                var allValues = response.getReturnValue();
                if (allValues != undefined && allValues.length > 0) {
                    opts.push({
                        class: "optionClass",
                        label: "--- None ---",
                        value: ""
                    });
                }
                for (var i = 0; i < allValues.length; i++) {
                    if(selectedVal == allValues[i])
                    {
                        opts.push({
                            class: "optionClass",
                            label: allValues[i],
                            value: allValues[i],
                            selected: "true"
                        });
                        var SelectPicklist = component.getEvent("PicklistSelected");
                        SelectPicklist.setParams({
                            SelectedValue: selectedVal
                        }).fire(); 
                    }
                    else
                    {
                        opts.push({
                            class: "optionClass",
                            label: allValues[i],
                            value: allValues[i],                          
                        });
                }
                }
                component.find(elementId).set("v.options", opts);
            }
        });
        $A.enqueueAction(action);
    }

})

PickListHelper.CSS
---------------------------
.THIS .optionClass {
    padding: .1rem;
}
.THIS .slds-select[size] option {
    padding: .1rem;
}
.THIS .slds-select[multiple] option {
    padding: .1rem;
}


Apex Controller:
----------------------
public class PicklstHelper {
    @AuraEnabled
    public static List < String > getselectOptions(String objectName, string fieldName) {
       List<String> optionsList = new List<String>();
       list <Schema.PicklistEntry>  piclistValueList = schema.getGlobalDescribe().get(objectName).getDescribe().fields.getMap().get(fieldName).getDescribe().getPicklistValues();
        for(Schema.PicklistEntry pickEntryObj:piclistValueList){
            optionsList.add(pickEntryObj.getValue());
        }
       
        return optionsList;
    }
}

AccountSave.cmp: (Component where we are going to utilize the above picklist Helper component)

<aura:component controller="AccountSavecls">
    <aura:attribute name="accountObj" type="Account" default="{'sobjectType': 'Account',
                          'Name':'','Type':''}"/>
    <div class="slds">        
        <div class="slds-card">
            <div class="slds-card__header slds-grid">
                <div class="slds-media__body">
                    <span class="slds-text-heading_small">Save Contact and Add it to table with checkbox selection</span>
                </div>
            </div>
            <div class="slds-card__body slds-card__body_inner">
                <ui:inputText class="slds-input" label="Name"  value="{!v.accountObj.Name}"/><br/>            
                <c:PickListHelper objectName="Account" 
                                  FieldName="Type" 
                                  FieldLabel="Account Type"
                                  SelectedValue="Customer - Direct"
                                  PicklistSelected="{!c.changeValue}"/><br/>
                <ui:button class="slds-button" press="{!c.saveAct}">Save Account</ui:button>
            </div>
        </div>   
    </div>
</aura:component>

AccountSaveController.js:
({
saveAct : function(component, event, helper) {       
        var actRec = component.get("v.accountObj");
var action = component.get("c.saveAccout");
        action.setParams({"actObj":actRec});
        action.setCallback(this,function(response){
            var result = response.getReturnValue();            
        });
        $A.enqueueAction(action);
},
    changeValue : function(component,event,helper){        
        component.set("v.accountObj.Type", event.getParam("SelectedValue"));
    }
})

AccountSaveApp.App;



output:
---------



References:
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_component.htm
https://trailhead.salesforce.com/modules/lex_dev_lc_basics/units/lex_dev_lc_basics_events
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/events_intro.htm








Thursday, 22 March 2018

Adding New contact to table dynamically and process selected contacts through check boxes in Lightning

Hi ,

Here we are going to learn how to save Record and then added to list which are displaying in the component on load.

In the table you can see check boxes for selecting multiple records and then process selected records.


Wrapper Class: Which holds Contact object and isSelected boolean variables to combine checkbox with contact record.

public class ContactWrapper{
        @Auraenabled
        public Contact contactObj;
        @Auraenabled
        public boolean isSelected;
}

Apex Class (Controller):

public class ContactCls {
  //retrieving contacts and return to the lightning component
    @Auraenabled
    public  static List<ContactWrapper> retrieveContacts(){
        List<ContactWrapper> contactWrapperList = new List<ContactWrapper>();
        for(Contact contactObj:[select id,firstName,LastName from Contact where firstName!=null order by createddate desc limit 6]){
            ContactWrapper contactWrapObj = new ContactWrapper();
            contactWrapObj.contactObj = contactObj;
            contactWrapObj.isSelected = false;
            contactWrapperList.add(contactWrapObj);
        }
        return contactWrapperList;
    }

//for sending contacts when we click on "Process Contacts" button along with checkbox selection
    @Auraenabled
    public static String updateContacts(String contactString){
        String ids = '';
        List<ContactWrapper> contactWrapList = (List<ContactWrapper>)JSON.deserialize(contactString, List<ContactWrapper>.class);
        for(ContactWrapper contacctWrapObj:contactWrapList){
            if(contacctWrapObj.isSelected){
                ids+=contacctWrapObj.contactObj.Id;
            }
        }
        return ids;
    }

//For saving contact record and returning the wrapper record to lightning component
    @Auraenabled
    public static ContactWrapper saveContact(Contact contObj){
        ContactWrapper contWrapperObj = new ContactWrapper();
        insert contObj;
        if(contObj.Id!=null){
            contWrapperObj.contactObj = contObj;
            contWrapperObj.isSelected = false;
        }
       
        return contWrapperObj;
    }

}



Lightning Component: Contact_Componen.cmp
-------------------------
<aura:component controller="ContactCls">
    <aura:attribute name="contObj" type="Contact" default="{'sobjectType':'Contact',
                                                             'FirstName':'',
                                                             'LastName':''}"/>
    <aura:attribute name="contactList" type="ContactWrapper[]"/>   
    <aura:handler name="init" value="{!this}" action="{!c.myAction}"/> 
    <div class="slds-card">
         <div class="slds-card__header slds-grid">
             <div class="slds-media__body">
        <span class="slds-text-heading_small">Save Contact and Add it to table with checkbox selection</span>
              </div>
        </div>
        <div class="slds-card__body slds-card__body_inner">
             <ui:inputText class="slds-input" label="First Name" value="{!v.contObj.FirstName}"/><br/>
             <ui:inputText class="slds-input" label="Last Name" value="{!v.contObj.LastName}"/><br/>
            <ui:button class="slds-button" press="{!c.contactSave}">Save</ui:button>
        </div>
    </div>
    <br/>
    <div class="slds-card">
         <div class="slds-card__body slds-card__body_inner">
<table class="slds-table slds-table_bordered slds-table_cell-buffer">
        <thead>
            <tr class="slds-text-title_caps">
                <th scope="col">
                    <div class="slds-truncate">Select</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="First Name">First Name</div>
                </th>
                <th scope="col">
                    <div class="slds-truncate" title="Last Name">Last Name</div>
                </th>               
            </tr>
        </thead> 
        <tbody>
        <aura:iteration items="{!v.contactList}" var="contactWrap" indexVar="index">
                <tr class="slds-text-title_caps">
                        <td>
                           <ui:inputCheckbox value="{!contactWrap.isSelected}"/>
                        </td>                                             
               
                        <td>
                            <ui:outputText value="{!contactWrap.contactObj.FirstName}"/>
                        </td>
                        <td>
                            <ui:outputText value="{!contactWrap.contactObj.LastName}"/>
                        </td>                                             
                </tr>
            </aura:iteration>
       
        </tbody>
    </table>
   
    <br/>
    <ui:button class="slds-button" press="{!c.updateSelectedContacts}">Process Contacts</ui:button>
        </div>
  </div>
</aura:component>

Controller: Conact_ComponentController.js
({
//for displaying contacts
     myAction : function(component, event, helper) {       
var action = component.get("c.retrieveContacts");
        action.setCallback(this,function(data){
            var result = data.getReturnValue();
            component.set("v.contactList",result);
        });
        $A.enqueueAction(action);
},
 //for processing selected contacts
    updateSelectedContacts : function(component,event,helper){
       var contactList = component.get("v.contactList");
       var action = component.get("c.updateContacts");
        action.setParams({"contactString":JSON.stringify(contactList)});
        action.setCallback(this,function(data){
            var result = data.getReturnValue();
            alert(result);
        });
        $A.enqueueAction(action);     
    },
  //for saving a contact and adding the same into list at 0th index by using "splice" method
    contactSave : function(component,event,helper){
        var contactObj = component.get("v.contObj");
        var contactsList = component.get("v.contactList");
        var action = component.get("c.saveContact");
        action.setParams({"contObj":contactObj});
        action.setCallback(this,function(data){
            var result = data.getReturnValue();         
            contactsList.splice(0,0,result);           
            component.set("v.contactList",contactsList);         
        })
        $A.enqueueAction(action);
    }
})


Lightning App: Contact_ComponentApp.app
---------------------
<aura:application implements="force:appHostable" extends="force:slds">
    <c:Conact_Component />
</aura:application>




Output:
----------



References:

https://www.w3schools.com/jsref/jsref_splice.asp (for splice method in javascript)
https://www.lightningdesignsystem.com/components/cards/
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/aura_compref_ui_inputCheckbox.htm
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/apex_records_save.htm




Monday, 19 March 2018

Display SVG Icon in Lightning Component ( Lightning Component Helper)

Hi ,



To display icons from salesforce.com in lightning we have to follow the below steps.



1) Creating the Lightning Component with the name "svgIcon"



 Create a new Lightning component from the menu: File > New > Lightning Component



2)Paste the following the code



Click on the COMPONENT tab, then paste:



<aura:component>
  <aura:attribute name="svgPath"        default="" type="String" description="the path for the icon in the static resource, this will be use in a SVG use tag" />
  <aura:attribute name="name"           default="" type="String" description="Symbol name of icon" />
  <aura:attribute name="class"          default="" type="String" description="the class of this SVG tag, can be use for CSS purpose" />
  <aura:attribute name="containerClass" default="" type="String" description="Container class name for span container of icon" />
  <aura:attribute name="category"       default="" type="String" description="Category of icon- action, standard, utility etc." />
  <aura:attribute name="size"           default="" type="String" description="Size of icon-- small, medium, large" />
  <aura:attribute name="assistiveText"  default="" type="String" description="Description name of icon" />
  <span aura:id="container" class="{!v.containerClass}">
    <span aura:id="assistiveText" class="slds-assistive-text">{!v.assistiveText}</span>
  </span>
</aura:component>



Click on the HELPER tab, then paste:

({
  renderIcon: function(component) {
    var prefix = "slds-";
    var svgns = "http://www.w3.org/2000/svg";
    var xlinkns = "http://www.w3.org/1999/xlink";
    var size = component.get("v.size");
    var name = component.get("v.name");
    var classname = component.get("v.class");
    var containerclass = component.get("v.containerClass");
    var category = component.get("v.category");

    var containerClassName = [
        prefix+"icon_container",
        prefix+"icon-"+category+"-"+name,
        containerclass
        ].join(' ');
    component.set("v.containerClass", containerClassName);

    var svgroot = document.createElementNS(svgns, "svg");
    var iconClassName = prefix+"icon "+prefix+"icon--" + size+" "+classname;
    svgroot.setAttribute("aria-hidden", "true");
    svgroot.setAttribute("class", iconClassName);
    svgroot.setAttribute("name", name);

    // Add an "href" attribute (using the "xlink" namespace)
    var shape = document.createElementNS(svgns, "use");
    shape.setAttributeNS(xlinkns, "href", component.get("v.svgPath"));
    svgroot.appendChild(shape);

    var container = component.find("container").getElement();
    container.insertBefore(svgroot, container.firstChild);
  }
})



Click on the RENDERER tab, then paste:



({
  render: function(component, helper) {
    // By default, after the component finished loading data/handling events,
    // it will call this render function this.superRender() will call the
    // render function in the parent component.
    var ret = this.superRender();

    // Calls the helper function to append the SVG icon
    helper.renderIcon(component);
    return ret;
  }
})







3.Use the New Component



Use your new component whenever you need an Lightning Design System SVG icon. For example, if your Static Resource is named SLDS you might use:



<c:svgIcon svgPath="/resource/SLDS/assets/icons/standard-sprite/svg/symbols.svg#user" category="standard" size="large" name="user" />


Example Component:
------------------------------

<aura:component >
<div class="slds-icon_container"> 
    <c:svgIcon svgPath="/resource/SLDS/assets/icons/standard-sprite/svg/symbols.svg#user" category="standard" size="large" name="user" />
    </div>
    <div class="slds-icon_container"> 
    <c:svgIcon svgPath="/resource/SLDS/assets/icons/standard-sprite/svg/symbols.svg#account" category="standard" size="large" name="account" class="slds-icon"/>
    </div>
     <div class="slds-icon_container"> 
    <c:svgIcon svgPath="/resource/SLDS/assets/icons/standard-sprite/svg/symbols.svg#contact" category="standard" size="large" name="contact" />
    </div>
</aura:component>

Output:
--------


References:
https://archive-2_1_4.lightningdesignsystem.com/resources/lightning-svg-icon-component-helper
https://trailhead.salesforce.com/en/modules/lightning_design_system/units/lightning-design-system5
https://www.lightningdesignsystem.com/icons/

What’s the difference between Einstein Article Recommendations and Suggested Articles?

How Does Einstein Article Recommendations Work? Einstein Article Recommendations helps support agents resolve customer cases efficiently by ...