Lightning in Salesforce – Part 3

Lightning in Salesforce – Part 3

In the previous post we learn how to use client side controller in lightning. In this post we will continue this with how to take input from user and process them between controller and save user inputs.

In lightning we have some native tags to get user inputs (Same as Visualforce tag or general HTML tag)


<ui:inputText aura:id="expname" label=" Account  Name"

value="{!v. account.Name}" required="true"/>

<ui:inputNumber aura:id="amount" label="Amount"

value="{!v. account.Amount__c}" required="true"/>

<ui:inputDate aura:id="expdate" label="Meeting  Date"

value="{!v. account.Date__c}" displayDatePicker="true"/>

<ui:inputCheckbox aura:id="reimbursed" label="Reimbursed?"

value="{!v.account.Reimbursed__c}"/>

<ui:button label=”Create Account” press=”{!c.clickCreateRecord}”/>

Then in the button click we will pass this data into controller for processing


clickCreateExpense: function(component, event, helper)

and now we can use helper to do some processing.


helper.createExpense(component, account); //account is instance of account

But now to save this we need to call apex controller. In apex we will use this format. So to call apex methods in Lightning we will follow this format

</pre>
@AuraEnabled

public static List<account > getaccount()
<pre>

Use @Auraenabled to access this method in Lightning. All method must be static so it’s stateless communication and faster then Visualforce Apex communication.

 

To get data from apex in lightning

// Load expenses from Salesforce

doInit: function(component, event, helper) {



// Create the action

var action = component.get("c.getaccount");

// Add callback behavior for when response is received

action.setCallback(this, function(response) {

var state = response.getState();

if (component.isValid() && state === "SUCCESS") {

component.set("v.account", response.getReturnValue());

}

else {

console.log("Failed with state: " + state);

}

});

// Send action off to be executed

$A.enqueueAction(action);

},

We will follow this approach to pass data in apex controller

createAccount: function(component, account) {

var action = component.get("c.saveAccount");

action.setParams({

"account": account

});

action.setCallback(this, function(response){

var state = response.getState();

if (component.isValid() && state === "SUCCESS") {

var accounts = component.get("v.accounts");

accounts.push(response.getReturnValue());

component.set("v.accounts", accounts);

}

});

$A.enqueueAction(action);

},

Here we use setparams to pass the parameter in apex and then use them in our code. So now we have good idea of how to pass data between Lightning and apex. So the last point in our journey is Events.

Event is used to pass data between one component and another.

In the Developer Console, select File | New | Lightning Event, and name the event “testEvent”

var createEvent = component.getEvent("testExpanse");

createEvent.setParams({ "account": newAccount });

createEvent.fire();

We will use fire() to fire the event and

 var newAccout = event.getParam("account"); 

is used to catch the events.

So here we cover all basic and starting points for development in sLightning. In my next post we will cover some advance uses of Lightning.

Do you have anything to say or want to add anything useful. Please share them in comments.

Advertisements

Lightning in Salesforce – Part 2

Lightning in Salesforce – Part 2

In the previous post we have discussed what is Lightning, Lightning app and some other basic details. In this post we will continue with Lightning component.

To create Lightning component first go to developer console select File | New | Lightning Component to create a new Lightning component. In the New Lightning Bundle panel, enter HelloWorld for the component name, and click Submit.Component

 

Now add this lightning component in the lightning app to view this in browser. A component is a bundle that includes a definition resource, written in markup, and may include additional, optional resources like a controller, stylesheet, and so on. A resource is sort of like a file, but stored in Salesforce rather than on a file system.

We will write our complete code in the lightning components.

Now we will learn to add attribute and expression this is a same process which we use in visual force components.


<c:helloMessage message="You look nice today."/>

Here message is an attribute and we will display it using component.


<aura:component>

<aura:attribute name="message" type="String"/>

Hello! {!v.message}

</aura:component>

This is a component body (looks similar to Visualforce component isn’t it).

Note: to display data we use v. expression format and this will remain same in all places. V is something called a value provider. Value providers are a way to group, encapsulate, and access related data. An expression is basically a formula, or a calculation, which you place within expression delimiters (“{!” and “}”). So, expressions look like the following:

{!<expression>}

 

You can also use labels and other text in expression


{!$Label.c.Greeting + v.message}

There are a number of different attribute types.

  1. Primitives data types, such as Boolean, Date, DateTime, Decimal, Double, Integer, Long, or String. The usual suspects in any programming language.
  2. Standard and custom Salesforce objects, such as Account, MyCustomObject__c.
  3. Collections, such as List, Map, and Set.
  4. Custom Apex classes.
  5. Framework-specific types, such as Aura.Component, or Aura.Component[].

 

Now we will learn how to use controllers.

Lightning component work on View-Controller-Controller-Model, or perhaps View-Controller-Controller-Database. Here two controller refer, one client side controller (JavaScript) and other is server side controller (Apex).


<ui:button label="You look nice today." press="{!c.handleClick}"/>

So when we click this button an event will fire (Same as Visual force) but instead of controller method we will first call client side controller or JavaScript controller.


({

handleClick: function(component, event, helper) {

var btnClicked = event.getSource();         // the button

var btnMessage = btnClicked.get("v.label"); // the button's label

component.set("v.message", btnMessage);     // update our message

}

})

This is the JavaScript controller format. Here event is which start this process. Component contains information related to the component in which this event is fired and helper is as name suggests a helper method which we can call multiple time in component.


handleClick2: function(component, event, helper) {

var newMessage = event.getSource().get("v.label");

component.set("v.message", newMessage);

},

handleClick3: function(component, event, helper) {

component.set("v.message", event.getSource().get("v.label"));

}

You can define multiple method but you need to separate them using comma. You can also use JavaScript debugging tools like console.log here to debug the application. In the next post we will learn how to take input from users and pass them in controllers.

Lightning in Salesforce – Part 1

Lightning in Salesforce – Part 1

We all are aware of Lighting and if not then we should. Because with every release Salesforce giving more focus to lightning. Lightning is the future (don’t worry Apex and Visual force will still available).

Those who don’t know what Lightning is for them “Lightning Components is a UI framework for developing web apps for mobile and desktop devices. It’s a modern framework for building single-page applications with dynamic, responsive user interfaces for Force.com apps. It uses JavaScript on the client side and Apex on the server side.”

lex_dev_lc_basics_architecture

 

Using lightning you can create Drag and drop component, Stand alone app, Run them in Visualforce page, Run them on other platform using lightning out and appexchange apps too. There are many good posts available on Internet and many resources too. So in this post (of series) I will pick short module and explain them separately. So that user can combine and use them as per their requirement.

So before we start here are some prerequisite:

  1. Create new Developer account.
  2. Enable custom domain and rollout this for user.
  3. Get basic Idea of JavaScript.

Now we will start the modules. In this series of post we will cover following thing.

  1. Lightning App
  2. Lightning component
  3. Attribute and expression
  4. Controller( JavaScript and apex)
  5. Use of helper
  6. Events

First we will start with Lightning App

Open the developer console and Select File | New | Lightning Application to create a new Lightning app. In the New Lightning Bundle panel, enter TestApp for the app name, and click Submit.

App contains the opening and closing tags for a Lightning app, <aura:application>. Between them, we will add all component and Save the app so that we can view the result.

APPPreview

 

The main items of an app are the following.

  1. When writing markup, you can add a component to an app, but you can’t add an app to another app, or an app to a component.
  2. An app has a standalone URL that you can access while testing, and which you can publish to your users. We often refer to these standalone apps as “my.app.”
  3. You can’t add apps to Lightning Experience or Salesforce1—you can only add components.

In the next part we will continue with Lightning components.

Be a Speaker at Dreamforce 16

Hi All, We all know about Dreamforce. Dreamforce is the biggest event of Salesforce in which we get to know lots of things, meet some industry expert and some very great sessions.

Speaking at Dreamforce is a fantastic experience and if you have ever attended, you know that the quality of session speakers is extremely high. If you are thinking for a Dreamforce speaker then here are a few tips and guidelines to give you an idea of what Salesforce looking for.

For 40 minute sessions, Salesforce looking for speakers that:

  1. Have a great story to tell and a passion for sharing your knowledge with others

  2. Provide clear successful use cases, best practices, teachings and how-to’s,

  3. Highlight the ROI and additional benefits your company and team has seen since implementing Salesforce

For our 20 minute theater sessions, Salesforce  looking for speakers that:

  1. Can highlight a tip or trick like “Use this shortcut to save 10 minutes a week”

  2. Tell a great customer success story

  3. Focus and/or highlight a specific feature and how you are using it

  4. A great demo

Here are a few helpful tips for crafting your speaker submission so that you get selected to speak.

  1. Outline your story – what are the key topics or points you want the audience to hear

  2. List and rank your top messages, target personas, target industries.

  3. On the submissions page, be as precise and descriptive as possible.

  4. Also share your past experience and your preference for a 20 or 40 minutes session.

You can do your registration here. All the best :).

Do you have anything to share let us know in comments section.

 

 

Connect Salesforce with Box.com Part 2

Connect Salesforce with Box.com Part 2

Hi All, In my previous post Connect Salesforce with Box.com (The Integration series) I have shared how can you create a Box.com app and authorize the user from Salesforce.

In this post I am sharing two utility method to create a folder on box.com and upload a file on box.com. There are various other methods are available but for starting I have found these two most useful.

So first create a folder in box.com platform you can use this method.


private void createfolder(String fileName, string parentid)
{
String url = 'https://api.box.com/2.0/folders';
string authorizationHeader = 'Bearer '+Accesstoken ;

HttpRequest req = new HttpRequest();
req.setheader('Authorization',authorizationHeader);
req.setBody('{"name":"'+fileName+'", "parent":{"id":"0"}}');
req.setMethod('POST');
req.setEndpoint(url);

Http h = new Http();
Httpresponse resp = h.send(req);
System.debug(resp.getbody()+'-----------------------'+resp); 
}

 

To upload a file in Box.com platform use this utility method.

 


private void uploadFileCode(String folderId,Attachment file,String token){
String boundary = '----------------------------356sdf986eff';
String header = '--'+boundary+'\nContent-Disposition: form-data; name=&quot;file&quot;; filename=&quot;'+fileName+'&quot;;\nContent-Type: application/octet-stream';

String footer = '--'+boundary+'--';
String headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
while(headerEncoded.endsWith('=')){
header+=' ';
headerEncoded = EncodingUtil.base64Encode(Blob.valueOf(header+'\r\n\r\n'));
}
String bodyEncoded = EncodingUtil.base64Encode(file.body);

Blob bodyBlob = null;
String last4Bytes = bodyEncoded.substring(bodyEncoded.length()-4,bodyEncoded.length());
if(last4Bytes.endsWith('==')) {

last4Bytes = last4Bytes.substring(0,2) + '0K';
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;

String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
} else if(last4Bytes.endsWith('=')) {
last4Bytes = last4Bytes.substring(0,3) + 'N';
bodyEncoded = bodyEncoded.substring(0,bodyEncoded.length()-4) + last4Bytes;

footer = '\n' + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
} else {
// Prepend the CR LF to the footer
footer = '\r\n' + footer;
String footerEncoded = EncodingUtil.base64Encode(Blob.valueOf(footer));
bodyBlob = EncodingUtil.base64Decode(headerEncoded+bodyEncoded+footerEncoded);
}

String sUrl = 'https://upload.box.com/api/2.0/files/content?parent_id='+folderId;
HttpRequest req = new HttpRequest();
req.setHeader('Content-Type','multipart/form-data; boundary='+boundary);
req.setMethod('POST');
req.setEndpoint(sUrl);
req.setBodyAsBlob(bodyBlob);
req.setTimeout(60000);
req.setHeader('Authorization', 'Bearer '+token);
req.setHeader('Content-Length',String.valueof(req.getBodyAsBlob().size()));
Http http = new Http();
HTTPResponse res = http.send(req);
System.debug(res.getbody()+'-----------------------'+res);
}

These are the two methods which you can use to create a folder and upload file.

Do you have anything to add or like this post or any other thing to share please share them in comments.

 

Connect Salesforce with Box.com

Connect Salesforce with Box.com

Hi All, We all know that’s how costly it is to store data in Salesforce.com. So we always want to store data in third party so that we can reduce the cost. Thats why today I am sharing the authorization process between Salesforce and Box.com in my Integration series.

For this first you need to go to Box.com for a Developer account which you can create here.

After successful account creation you need to create an App to get the key and token. You can create an app here.

After creation your app will look like this.

Screenshot_6

 

 

Give your Visualforce page url as redirect URL. Now use the below code to perform the authorization process.

Controller:

public with sharing class BoxComIntegration {
    //Fetched from URL
    private String code ;
    private string key = 'llpm**************2ks8';
    private string secret = 'LMh**************jCmK2fDHK' ;
    private string redirect_uri = 'https://c.ap1.visual.force.com/apex/BoxComUpload';
    
    public BoxComIntegration()
    {
        code = ApexPages.currentPage().getParameters().get('code') ;  
        //Get the access token once we have code
        if(code != '' && code != null)
        {
            AccessToken() ;
        }
        
    }
    
    public PageReference BoxAuth()
    {
        //Authenticating
        PageReference pg = new PageReference(BoxAuthUri (key , redirect_uri)) ;
        return pg ;
    }
    
    public String BoxAuthUri(String Clientkey,String redirect_uri)
    {
        String key = EncodingUtil.urlEncode(Clientkey,'UTF-8');
        String uri = EncodingUtil.urlEncode(redirect_uri,'UTF-8');
        String authuri = '';
        authuri = 'https://account.box.com/api/oauth2/authorize?'+
        'client_id='+key+
        '&response_type=code'+
        '&redirect_uri='+uri+
        '&state=security_token%3D138r5719ru3e1%26urldfrgdgvrev';
        
        return authuri;
    }
    
    
    public void AccessToken()
    {
        //Getting access token from google
        HttpRequest req = new HttpRequest();
        req.setMethod('POST');
        req.setEndpoint('https://api.box.com/oauth2/token');
        String messageBody = 'code='+code+'&client_id='+key+'&client_secret='+secret+'&redirect_uri='+redirect_uri+'&grant_type=authorization_code';
        req.setHeader('Content-length', String.valueOf(messageBody.length()));
        req.setBody(messageBody);
        req.setTimeout(60*1000);

        Http h = new Http();
        String resp;
        HttpResponse res = h.send(req);
        resp = res.getBody();
         Map<String,object> responseMap =(Map<String,object>)JSON.deserializeUntyped(res.getBody()) ;  
          String token =  String.valueOf(responseMap.get('access_token'));
         system.debug('***************'+token);
   }
}

VF Page:

<apex:page controller="BoxComIntegration">
<apex:form >
    <apex:pageblock > 
        <apex:commandbutton action="{!BoxAuth}" value="Authentication">
    </apex:commandbutton></apex:pageblock>
</apex:form>
</apex:page>

Screenshot_7

Also add two Base URLs in remote site setting. And now you are all set when you run this code you will get access token and using that token you can easily upload, download the files.

Screenshot_8

Let me know if you like this post. Do you have anything to add in the post. let me know in comments section.

Also check second post of Integration series connect salesforce with box com part 2