Thursday, 5 November 2015

Using Lighting Out with Visualforce

Lightning out is awesome feature and it is correct way of integrating mashups .With lightning out one can easily take lightning components outside salesforce .Some of the examples of system that can consume this includes Heruko , SAP ,Sharepoint and so on .

For external system mashup you will need to first establish connection with SFDC using connected apps .

There is an excellent  session on this topic .

 I have found multiple blogs demonstrating the concept where the lightning component attribute is set from the data inside visualforce .Some of them are as below

Balkishankachawa.wordpress.com/2015/10/31/lightning-component-javascript-remoting-and-visualforce-page/

http://peterknolle.com/lightning-components-in-visualforce/

In this blog we will see how to get the component values out of lightning into our Javascript variable so that we can continue with  more fun of mixing Visualforce and lightning components .

USE CASE :::

My entire Visualforce page used no apex:form and it used pure HTML ,SLDS CSS and Javascript remoting for actions .Now comes the big change in requirement ,need Rich text input field .

I googled to figure if HTML-5 has rich text fields or are there any native solutions without adding the apex:form element and apex:textarea .Introduction of apex:form implies lot of viewstate and makes page slow .

Lightning components interestingly provide "ui:inputRichText"  which is rich text on the webform  .Exciting !!! ..Now comes the challenge of integrating the lightning component into the visualforce and then grabing the set text from the lighting component back into visualforce .

Using lightning out we can integrate a component into visualforce with few lines of javascript .

We will also see how to use the callback function provided to grab the component attribute value back into our visualforce page 

COMPONENT CODE::

If you are familiar with lightning components its 101 of that .A simple component being embedded .

LIGHTNING DEPENDENT APP:

This is similar to declaring dependency just like how we write import statements in java or node.

VISUALFORCE CODE::

The most important part of visualforce code here is way we have declared a javascript variable and pulled the Component into  global variable to access it outside the component and use right away in our visualforce

         var richtext;
             $Lightning.use("c:RichtextApp", function() {
                 $Lightning.createComponent("c:Richtextcmp", {},
                     "richTextEditor",
                     function(cmp) {
                         // do some stuff
                         richtext = cmp;//Very important
                     });

             });

The final screens are below













The console.log clearly prints the what ever is typed in the editor showing how easy it is to get values out of the lightning component.

Sunday, 1 November 2015

Using Jquery with SLDS for validation and Error Display

Recently I have been playing around with SLDS  design system and for sure this has better component set for building mordern applications with excellent look and feel for Mobile or desktop .

One of the key challenges using this library in visualforce (Not in lightning components) is there is no javascript support for CSS unlike bootstrap  and hence it makes really difficult .This is initial stage and I am sure as more developers dig into this ,they will come up with Javascript for various components .

One reason why SFDC would have left this as an exercise to community is since there are wide variety of frameworks now and each Javascript framework is evolving on its own .Angular is moving towards Angular 2 and React is still in its intial phases (Although this framework is widely adapted now and has its own advantages and flexibility).

Lightning components on the other hand is also fairly new but event driven patterns makes it easier to communicate with server .Lightning components will definitely work well with SLDS and there are already some attempts made to build some components .

Check the below project in Trailhead and its a good starting point to get started with using SLDS in lightning components


I tried playing with SLDS with jquery and feel using simple jquery with SLDS can be really cool architecture to build simple applications .Again i dont say it may scale well and you will see for larger applications it will be better to go with  frameworks .

Aim of this blogpost is to demonstrate a simple plugin that i have built that can handle client side validations and also you can display error or success in SLDS style .

The source code for the plugin is available at below gist 


Lets walk through a simple use case on how to use this .

For demonstration purpose we will building a simple form with SLDS design system and a small apex class that calls a Javascript remoting function to insert Account.

We will need three libraries installed to see a working demo

The apex code for ease of our eyes is below

Plugin set up Instructions

All the visualforce coder needs to handle  in HTML of input tag is to add two extra  attributes declaratively

  1. data-required (Make this to true if you want the field to be required)
  2. data-fieldName (Field label that will be displayed as error )
In Javascript remoting you will just wrap your remoting call with below

if (!validatorSLDSplugin.validate()) {

}


Sample screenshot of how this looks




To display success or error messages or any messages on the screen invoke the validator function display alert as below with message and message class .Note message class has to be from the SLDS library .

From SLDS library the classes are as below
  • success--slds-notify slds-notify--alert slds-theme--success slds-theme--alert-texture
  • failure ---slds-notify slds-notify--alert slds-theme--error slds-theme--alert-texture
  • info ---slds-notify slds-notify--alert slds-theme--inverse-text slds-theme--alert-texture
A sample example of how to invoke the validator is as below for success message

validatorSLDSplugin.displayalert('Record created with Id..'+result.Id ,'slds-notify slds-notify--alert slds-theme--success slds-theme--alert-texture'); Sample screenshot of how this looks
Handling SVG images

One of the pain points of the new SLDS has been how we handle SVG .I ran into an issue where using jquery append function did not work with SVG .To overcome this we have refresh the HTML section again .

The refresh can be done as below in Jquery

j$("#messagewrapper").html(j$("#messagewrapper").html());


I also think same solution can be applied to action:function when re rendering SVG tags .A jquery call needs to be made again with outputPanel surrounded and in oncomplete function refreshing the HTML using jquery .I have not tried this but would love to try and see .(If any of you got leisure time try this and let me know how this goes)

Also observe the image variable that i have used in my page to pass the dynamic URL as a global window object to the plugin .

var imageURL = "{!URLFOR($Resource.SLDS102, 'assets/icons/action-sprite/svg/symbols.svg#close')}";

I hope you enjoyed this post .

This is start and i guess it would be great if all SLDS components can be wrapped with jquery or probably angular directives or react components .Visualforce is amazing tool and for building simple mobile friendly pages ,using Javascript remoting with SLDS and VF would work well with rapid development time .



Sunday, 4 October 2015

Setting up Dev tools for Salesforce Project that uses ReactJs library

Problem Statement :

You are building a visualforce page which has React JS library and you want to split your React code into multiple files as per javascript best practices and maintain your React JS folder inside your mavensmate project .You need your tooling to help you with local development in offline as well you are in search of a convenient mechanism to handle pushing your changes to SFDC static resource with minimum effort . 


The static resource once zipped in salesforce ,its hard to edit even for awesome tools like mavensmate .Mavensmate tool is a well known IDE and it comes with resource bundle for this process where one can create a bundle with JS ,CSS and image files and then convert these bundles to the static resource .


This process will not work for the React JS files as React JSX needs to be transformed into JS files before the actual code is shipped to the Production .


There are multiple ways to solve this tooling problem and in this post we  will set up our tools for salesforce project using combination of gulp and mavensmate


Prerequisite:

  1. You have node installed in your system
  2. You understand gulp.js (Using gulp you can automate your workflow build for JavaScript Projects)
  3. You are in process of learning React JS and understand the library
  4. You are familiar with mavensmate IDE for apex and visualforce development
In my last article we created a simple page with React and all code was inside the single visualforce page  making it harder to maintain and debug .We will use the same Visualforce page and I will walk through the process of how we can be more structured and modular making life simpler for debugging and deploying and of course having fun by doing development locally .

To get started you can clone the repo below and have gulpfile.js and package.json copied to your project folder and also you can create a sample folder structure for ReactJs as per my git project

Observe the gulp file ,it has two major tasks

1)Build task



This will create a separate folder dist/build and concatenate all JS react modules using browserify(Browserify will transform using JSX to JS files) .Also note in JSX files how we have used require and module.exports function .If you are familiar with node.js this is common pattern to export module and configure dependencies .


2)Zip task



This task will zip our final JS files from build folder and place in our mavensmate static resource folder .Note its ideal to create Static resource on server (Salesforce)and sync to mavensmate so that you have meta xml .Else you will need to create your own meta xml for pushing from mavensmate.(Remember deployment to salesforce need meta xml for each component ).


You will need  node now and once you have package.json and the gulpfile.js you can run install command to have all node modules and dependency configured on your local machine


npm install 

  • Keep your static resource file name and the file name in the gulp file path

Observe the RESOURCE_NAME Parameter and it has same name as static resource and its key assumption here .

Following are the three process you will need to follow once you change code to sync to salesforce server


1)Run gulp build

2)Run gulp zip
3)Save mavensmate static resource file

Note :You can set up gulp default and configure both to happen in one command but my personal preference is to go step by step .

Notice that from previous sample our entire visualforce is reduced so much



To make more things clear lets watch it in action the flow of tooling workflow .You can check my  git repo for entire work 



This is not the end of the world .You can further use jsforce and automate further .Also you can set up gulp watch task to watch only for changes and run your process automatically and deploy to salesforce.

Kindly note that this process or having gulp set up you can do more magical stuff and become efficient .

Lot to expore.Need to make some time and kick some ass :) .I hope you enjoyed this small blog and thanks for your time .

Monday, 21 September 2015

ReactJS and Salesforce Lightning SLDS 101




Having worked on writing visualforce page with React using Salesforce Lighting Design System I would like to share some experience  through this blog post.

Clearly  ReactJs can cherry pick difference in the DOM structure and updates the only part of DOM that is part of component, you read this post to know little in detail about ReactJs on getting started and understaning basics.

ReactJs with Remote Objects

Salesforce Remote Objects allows you query salesforce without glueing apex and purely writing UI intensive apps see here. I wrote code snippet that consume remote object and query salesforce, on top of it, he have imported Lighting Design System to fabricate the UI.


Salesforce Lighting Design System (CSS from Salesforce)

Salesforce have opened stylesheets now, for the world to incorporate Salesforce user experience with new Lighting UI. Out of the many components available, I will be using datatable component and header components to carve the layout of this page.


Single Page Application (SPA)

To showcase, component driven functionality with React, I wrote single page, keeping concepts simply to absorb, to give a kick start and direction for consuming this framework in the universe of Salesforce.Below is visualforce page that consume React component, click below to open in new page




Code Walkthrough

If you carefully notice, we reference all external javascript through CDN and some hosted on github, learn how to use Github as CDN with Salesforce.



The components are divided from top to bottom in two prime category of components nested

1. Account View : Parent component nesting child component
2. Account List : Child component polling Salesforce to list data rows

To visualize neatly you can see this tree structure shown below

  --Accountview
      ---AccountList
--Account 1
--Account 2
--Account 3


As you can see three component are primary designed here, Account Component is component to draw header of the table (list) declared as below


Secondly, AccountView is nesting drawing the view of table and nesting list component that queries Salesforce in the back




AccountList binds data into Tabular view and generates table



Notice, the use of  promises with Visualforce Remote Objects using code from in this repo (check it out) and not a single line of html code is written on visualforce end besides skeleton of the page, all code is written in JSX compiled into Javascript, also note for converting React JSX to javascript in production release, you can do it through Node React Tool


Whole code snippet is embedded below is ready to be served out of the box (import all required resources from CDN)


Wednesday, 2 September 2015

Migrating to Lightning Experience with Trailhead

I have been fan of Trailhead since I used it for first time to learn on how to build lightning components .Trailhead makes learning fun and enjoyable .You get to learn at your own pace at your own time and at your convenience .

Many of you would have heard salesforce launching new User Experience which is seamless experience of your salesforce data on any device size ,right from your apple watch to your apple macbook pro or air .

Migration is always not easy .Its cultural change .It will come with time and people will require some support and Training to get trained .

Trailhead is our friend that will guide us in right path as we transition from our aloha look and feel to this new exciting lightning experience .Whether you are Developer ,Architect ,Customer or Partner related to Salesforce ,Trailhead has content for everyone .

Lets Summarize the content that will make you feel confident and comfortable while you go through each of these  new modules in the Trailhead

Admin Trail




For Admins Migration to lightning experience means they need to be familiar with below


  1. How can they customize or change layouts ?
  2. How can they configure objects and relationships?
  3. How can they enable their users to this new experience ?
  4. What should be the Roll out strategy while they migrate the users to new experience ?
  5. Where can they configure actions and what are the differences with respect to old aloha UI ?
Lot to answer.If an admin goes through all the modules present in above Trailhead I am sure you will get to the meat of the content .

Developer Trail


With new Lightning ,Developers will need to worry about following 

1)What will break in their existing code and wont work with lightning ?
2)How can they make their Visualforce code work with lightning ?
3)What is Salesforce Lightning Design System ?
4)How can they detect via code how to differentiate between aloha environment and lightning environment ?
5)If you are an ISV ,what factors you have to consider when you build your visualforce pages ?
6)What changes app exchange packages will need to get the Lightning Certified Sash?

All the answers to this has been embedded inside the Developer Trail for Lightning experience .

Sales Rep Training


Sales Rep Trail will enable your organization to train your sales reps 

Asking Sales Rep to go through this Trail will help them use the system effectively .Your sales rep will learn below in detail

  1. How to work with leads and opportunities with new user experience 
  2. Various tools that will help them to track their performance and help them sell effectively
  3. New reports and dashboards and chatter feeds .
This is the first content for end users from Trailhead team and step definitely in right direction

If you are a new admin there is one more and you can start right from there 


Trailhead URL


Also don't forget to share your progress on twitter and share your badge selfie as I do often 



















If you love projects ,there are few new projects as well  for you 

https://developer.salesforce.com/trailhead/projects

Sunday, 16 August 2015

Lightning Connect Apex Adaptor

If your organization has already subscribed to the Lighting Connect feature(This is available based on Subscription with additional fees .Contact your salesforce AE to learn more ) to create External Objects,it is good to know that apex can be used by your developer to expose data from any system which uses SOAP or REST as external Objects .

The advantage of using External Objects will be saving some storage space .The data will not reside inside salesforce but can be viewed in salesforce User Interface just like any other objects .

There are number of limitations worth noting before you decide to go with external objects and salesforce documentation can help you in regards to this 


There are lot of chances that you need data only for reading from external system and may later run apex to convert few into transaction data .One of the ways to address this business use case can be using lightning connect .There may be millions of data and with lightning connect you can keep it outside salesforce but still use salesforce interface to view ,search and use apex to convert some to SFDC native objects .

When lightning connect feature was launched you needed an adaptor to convert data into Odata before you could actually consume and bring into salesforce as an external object.

Its good to know you dont need an Odata now and an apex written by developer can be used by salesforce administrators to bring any data via SOAP or REST to salesforce .



Aim of the blog Post:

   The main aim of this blog post to show an example to developer community on how to extend  data source provider and data source Connection classes to build external data source in salesforce.

We will connect to a simple REST end point available for Non commercial financial  purpose .To explore more about this webservice please read below 


Exchangerate Lab provides us free end point for non commercial use to fetch some data that shows latest currency rates for selected Currencies .Please note the aim of calling this webservice is just to demonstrate the Lightning connect feature.


  • The first step is to create a DataSource Connection class.

The Connection class will provide 
  1. Metadata definition of the external schema which admin of salesforce will generate based on need by just clicking a button
  2. Query method to query the data from API.
  3. Search method to implement the search via global search
  4. Filters and pagination if needed can be implemented in query and search methods
  5. Write a JSON parser for mapping data to fields
The below code is self explanatory and it connects to exchangedate labs to fetch currencies and exchange rates


  • The next step is to create a Data source Provider class that describes the functional  abilities like authentication mechanism ,capabilities provided by the data source
The below code shows an example class and format 

The below shows the video on how Admin will configure with simple clicks for magic 




References:

https://help.salesforce.com/HTViewHelpDoc?id=limits_external_data.htm&language=en_US

https://developer.salesforce.com/blogs/engineering/2015/05/introducing-lightning-connect-custom-adapters.html

http://docs.releasenotes.salesforce.com/en-us/summer15/release-notes/rn_forcecom_external_data_apex_adapter.htm

Monday, 10 August 2015

TrailHead Goodness

Most of my friends who come from Java world into apex often ask me about where can they find quick tutorial on CRM lifecycle and quick hands on tutorial on how to use Account Management ,Contact Management ,opportunity management and so on.

TrailHead has got some modules now to explain all of this in depth .

Lets summarize each of the modules and see what they help us learn

Account & Contacts














If you quickly want to learn how to create some Test Accounts and Contacts and understand relationship among them worth spending your half an hour with this module


CRM Basics














Now this may sound silly if you know the concepts but fact is most of developers we dont think of business case for which we spent hours writing code .The basics of salesforce starts with knowing CRM .This module for me should have been first module of TrailHead .Never too late .Grab a coffee and spend some time working on this Trail Badge .


Leads and Opportunities














I would open this module for Training end users .Before we onboard our sales or marketting team ask them to get this badge and I am sure this will help them to gain better understanding on how salesforce will increase their productivity.Explain them the significance of keeping data clean and ask them to create some test data in training environment before they start using the system in their Production Environment .

Event Monitoring

If you are a system architect I would recommend you to learn more about Event Monitoring module .This will give you great insight of how to track various events like login ,logout ,usage of API ,UI clicks .All this will help to draw inference about how the system you have built is being adopted .

Adoption is key metric and this module will help you understand how to pull event log files from SFDC and how to report and analyze reports .















Finally if you are going to dreamforce how cool it is to gather information prior to that and do some homework.Dreamforce module is amazing way to prepare you for this .















If you are a geek and Nerd ,then do some Projects and get hands dirty .Follow the Trailhead Project link below

https://developer.salesforce.com/trailhead/projects

Finally grab all Trailhead badges as I did and beat me up :))




Introducing Lightning Base Components

Lightning Base Components are great addition to the platform and in fact revolutionary .One of the concerns around lightning component ...