Add Lightning Components In UI

Add Lightning Components In UI

In my Last post we learn the basic of lightning and components. Today we will continue with where we can use them.

We can use lightning component in 4 places.

  1. Lightning App
  2. Salesforce 1
  3. Lightning Experience
  4. Visualforce

We all know how to use Lightning component in Lightning App. Today we learn to use lightning component in all remaining places.

Add Lightning Components to Salesforce1

Make your Lightning components available for Salesforce1 users.

In the component you wish to add, include implements=”force:appHostable” in your

aura:component tag and save your changes.

<aura:component implements=”force:appHostable”>

The appHostable interface makes the component available as a custom tab.

Use the Developer Console to create Lightning components.

Include your components in the Salesforce1 navigation menu by following these steps.

  1. Create a custom Lightning component tab for the component. From Setup, enter Tabs in the Quick Find box, then select Tabs.

Note: You must create a custom Lightning component tab before you can add your component to the Salesforce1 navigation menu. Accessing your Lightning component from the full Salesforce site is not supported.

  1. Add your Lightning component to the Salesforce1 navigation menu.
  2. From Setup, enter Navigation in the Quick Find box, then select Salesforce1 Navigation.
  3. Select the custom tab you just created and click Add.
  4. Sort items by selecting them and clicking Up or Down.

In the navigation menu, items appear in the order you specify. The first item in the Selected list becomes your users’ Salesforce1 landing page.

  1. Check your output by going to the Salesforce1 mobile browser app. Your new menu item should appear in the navigation menu.

Add Lightning Components to Lightning Experience

In the components you wish to include in Lightning Experience, add

implements=”force:appHostable” in the aura:component tag and save your

changes.

<aura:component implements=”force:appHostable”>

Use the Developer Console to create Lightning components.

Follow these steps to include your components in Lightning Experience and make them available to users in your organization.

  1. Create a custom tab for this component.
  2. From Setup, enter Tabs in the Quick Find box, then select Tabs.
  3. Click New in the Lightning Component Tabs related list.
  4. Select the Lightning component that you want to make available to users.
  5. Enter a label to display on the tab.
  6. Select the tab style and click Next.
  7. When prompted to add the tab to profiles, accept the default and click Save.
  8. Add your Lightning components to the App Launcher.
  9. From Setup, enter Apps in the Quick Find box, then select Apps.
  10. Click New. Select Custom app and then click Next.
  11. Enter Lightning for App Labeland click Next.
  12. In the Available Tabs dropdown menu, select the Lightning Component tab you created and click the right arrow button

to add it to the custom app.

  1. Click Next. Select the Visible checkbox to assign the app to profiles and then Save.

Using Components Add Lightning Components to Lightning Experience

  1. Check your output by navigating to the App Launcher in Lightning Experience. Your custom app should appear in theApp Launcher.

Click the custom app to see the components you added.

Use Lightning Components in Visualforce Pages

Add Lightning components to your Visualforce pages to combine features you’ve built using both solutions. Implement new functionality

using Lightning components and then use it with existing Visualforce pages.

There are three steps to add Lightning components to a Visualforce page.

  1. Add the <apex:includeLightning /> component to your Visualforce page.
  2. Reference a Lightning app that declares your component dependencies with $Lightning.use().
  3. Write a function that creates the component on the page with $Lightning.createComponent().

Adding <apex:includeLightning>

Add <apex:includeLightning /> at the beginning of your page. This component loads the JavaScript file used by Lightning

Components for Visualforce.

Referencing a Lightning App

To use Lightning Components for Visualforce, define component dependencies by referencing a Lightning dependency app. This app

is globally accessible and extends ltng:outApp. The app declares dependencies on any Lightning definitions (like components)

that it uses. Here’s an example of a simple app called lcvfTest.app. The app uses the <aura:dependency> tag to indicate

that it uses the standard Lightning component, ui:button.

<aura:application access=”GLOBAL” extends=”ltng:outApp”>

<aura:dependency resource=”ui:button”/>

</aura:application>

To reference this app, use the following markup where theNamespace is the namespace prefix for the app. That is, either your org’s

namespace, or the namespace of the managed package that provides the app.

$Lightning.use(“theNamespace:lcvfTest”, function() {});

If the app is defined in your org (that is, not in a managed package), you can use the default “c” namespace instead, as shown in the

next example. If your org doesn’t have a namespace defined, you must use the default namespace.

Creating a Component on a Page

Finally, create your component on a page using $Lightning.createComponent(String type, Object attributes,

String locator, function callback). This function is similar to $A.createComponent(), but includes an additional

parameter, domLocator, which specifies the DOM element where you want the component inserted.

Let’s look at a sample Visualforce page that creates a ui:button using the lcvfTest.app from the previous example.

<apex:page>

<apex:includeLightning />

<div id=”lightning” />

Using Components Use Lightning Components in Visualforce Pages

$Lightning.use(“c:lcvfTest”, function() {

$Lightning.createComponent(“ui:button”,

{ label : “Press Me!” },

“lightning”,

function(cmp) {

// do some stuff

});

});

</apex:page>

This code creates a DOM element with the ID “lightning”, which is then referenced in the $Lightning.createComponent()

method. This method creates a ui:button that says “Press Me!”, and then executes the callback function.

Important: You can call $Lightning.use() multiple times on a page, but all calls must reference the same Lightning dependency app.

Advertisements

Salesforce + Drucker School, A must read Trail

Trailhead is always fun to learn. Salesforce regularly updates the trailhead modules, adds new challenge and add new rewards as well. Recently Salesforce launches superbadge concept in which you can show your talent using them. But recently Salesforce launches a new module “Learn Drucker School MBA Essentials” .

Because Salesforce is a customer centric company and Drucker School is a management school based on the cornerstone idea that the purpose of an organization is to create and keep a customer. So now they both combine their hands and make a module in which user learn how to keep their customer happy and implement all the requirement in Salesforce at the same time.

Using this module you will learn what are the key points which we should keep in mind when we create something for our customer and at the same time we can implement that in Salesforce so that at the end we can make our customer happy. Because a Happy customer is the key of success and you will never fail if your customers are happy and they are with you. So you should check this trail.

This module is divided into five parts and it’s a short one (So go ahead and try this). So this module uses the MBA course curriculum and implements them using some real life scenario and implements the requirements in Salesforce.

dsm_mod1_unit1_1_trail_wheel

 

This is a great knowledge which everyone should have to keep their customer happy and at the same time help their business grow much faster. This module uses Five points theory  of Five questions we should ask to our self to understand the customer requirement  and the questions are What is purpose, Who is our target customer, what do our customer value, what are the results and what are the plans. Based on these five questions you can easily find that what your main purpose of developing any solution and who will use it. This will help us to understand who is our audience is and what they really need and we are delivering the same product for which they have asked. And will we ever get the response which we have expected also if there are some existing products in market so will customer buy our product. Then the most important part is what the end result is and what our future plans are to handle the results.

At the same time we can implement all these functionality in Salesforce like if its a customer portal where they ask for some help then we can use Service cloud, If we want to sell something then sales cloud, If we want to go with mobile then app cloud or process the data then we will use the Analytic cloud and wave. Then we can use many Salesforce inbuilt tools like Workflow and process builders for automation of email sending, Fields updates, outbound message to communicate with external servers and Task to notify peoples, Approval process for Approval functionality , Console for easy handling of Case and CTI and call center to implement call centers in Salesforce or Marketing cloud to handle all the current marketing skills, Analytic cloud to generate and process on Data and create reports or App cloud to inbuilt support of App development on All major platform and because future is mobile ready so your solution will be future ready itself or can use the newly addition Lighting to get the better UI experience for the customer.

If I cover all the points then this post will never ends so better part is just and complete this module and did I informed you that 500 early birds will get a certificate from the Drucker MBA schools. Great news isn’t it so hurry up and share your badge and the certificate with the world. All the best 🙂

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.

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.