Monday, 6 October 2025

My AI Channel


Hi Folks, 


Its been a while posted any post on Salesforce. I feel like Salesforce can waith but new AI hype cant, need to go with the flow. 

I would request all of you to give a glance on my channel. Lot of the channels have lot of good conetnt but a review on ithis channel would be greatly appreciated. This is not copied from chatGPT. Its my own ideas that have ben flowing since the 2012. While I have started the journey and learning have a mountain of things to cover. Please support this channel in my learning curve. 



Friday, 10 November 2023

oAuth Use Case -  Headless API

Explained in the Easiest way


Wondering why? and When we use the Headless API flow


Use case example:

Imagine a company that uses Salesforce as its primary CRM platform. The company also maintains a separate customer portal that is hosted on a different server. The goal is to allow the customer portal to access Salesforce data and perform certain operations, such as retrieving customer information or updating records, without requiring manual user intervention.


Now in a simple and easy example decoded below:- 

Imagine:

You own a fancy showroom, and you've hired a reliable person (a third-party app) to pick up items after business hours.


Problem: The showroom is Closed


1. Authorization Call (Requesting Access):

The person arrives at your showroom, but it's closed. He calls you (the owner) and says, "I can't get in; the showroom is closed!" In the digital world, this is like the person making an "Authorization Call" by visiting a special URL: /services/oAuth2/authorize. It's like him asking for permission to access.


2. Admin (Owner) Intervention:

You, being the owner and having all the access, give him a special code (like an OAuth authorization code). It's your way of saying, "Okay, here's the secret code to open the lock."


3. Access Code Delivery (Getting the Digital Key):

The person receives the code and enters it at the showroom door. Now, instead of directly unlocking the door, the code triggers a system to send an SMS or email (access token) to the person. This is like a digital key being delivered through a special URL: /services/token. It's the final piece that allows him to access the showroom.


4. Entering the Showroom:

With the access token received on his phone, the person can enter the showroom without you physically handing him a key. It's like a digital key that grants access.


Benefits in Simple Terms:


Smooth Access: The person gets access to the showroom even if it's closed, just by using the special code and the digital key (access token).


Owner Control: As the owner, you control who gets the special code. It's not a physical key, but it works like one, and you can change it anytime.


No Need for Physical Keys: The person doesn't need a physical key; the code and digital key make the process seamless and secure.


Note:- 

All the information and step-by-step guide are available here 
https://resources.docs.salesforce.com/246/latest/en-us/sfdc/pdf/headless_identity_impl_guide.pdf

Wednesday, 30 September 2020

Avoid hitting maximum CPU time Limit error in Salesforce Using Before Save flows

Hi Folks,

The trending word is COVID-19.

Do you want me to talk about this? Naaah! Tired of Hearing CORONA.

Let's get to the business people. Before SAVE FLOWS. Yes, you read that right. Salesforce has introduced an awesome features and added one more vanilla and chocolate for the team called Functional/Implementation Consultants(IC's). Yeah, in Summer 20. 

For functional people working in Salesforce, now they have a new weapon. Flows can work before insert and before update calls.

There are a lot of benefits of using flows rather than using the trigger. Let's take them now:-

  1. Less Code and more config.
  2. Update New and Changed Records 10 Times Faster by Using Before-Save Updates in Flows.
  3. Save CPU time.  HOW??
As per salesforce, this vanilla feature(Before Save Flows), actually runs prior to the before triggers and it saves the round of assignment rules, auto-response rules, workflow rules, and other customizations that take time to execute.

Well, don't get excited, before you implement for your client read the considerations of flows.

https://help.salesforce.com/articleView?id=000314438&language=en_US&type=1&mode=1

Enjoy and keep learning more every day! 




Thursday, 26 December 2019

Salesforce Evergreen functions (Server less functions) - Open Sourcing

Hi Folks,

As another year is ticking down and going towards another shiny year ahead. I am sharing this post for salesforce beginners and not for the experts(Are you an expert think again 🤔🤔🤔) who are keen to know what is happening around Salesforce world. Yes, I say world where we are people helping each other as a community which is thriving to learn and prosper.

Let me start with Dreamforce 2019!  It was fabulous. No No don't judge, I didn't got a chance to visit, but I know it was an awesome event.

Salesforce had a spectacular event this year in November 2019 at  San Francisco, US. Around 170,000 attendees across the globe. It took all over the SF and salesforce had to bring ships at the port to accommodate the people. 

Well, there is lot you can read about salesforce event Dreamforce '19 that happened last month online. 

Its been again a long time I have shared or written any blog post. One of my colleague mentioned me about EverGreen functions and the competition ahead for developer like us. 

Yes, Evergreen 🌲🌲🌲 function yeah , you heard that right. 

Salesforce has opened the doors for not just apex coding but also for the developers working on core technologies like Java and Nodejs. 

🤯🤯🤯🤯🤯🤯🤯🤯

If you are a Salesforce developer then you must gear for more competition and yes of course, never ending learning , which is good for career growth. 

👍👍👍👍👍👍



EverGreen Functions


Evergreen functions are going to be a game changer altogether and the way developers are actually coding. 

 These Evergreen functions will be manged by Kubernetes (another open source tool), we will get on this later, which will be a big treat for our Java developers and of course Node.js developers. 
It is going to be a competition and a big scope of learning for salesforce developers.
Now, as per salesforce Evergreen functions will be very much a follower of Architectural design patterns.

I would like to talk about few of which Evergreen functions are capable of and supports . I have just listed few of them below:-


  • Function as a Service:- Obviously, the logic of your application and processing the events will not be depending only on Apex, rather it will use the same packaging methods of apex for JAVA and Node js also. These evergreen functions can be directly called from apex or from Platform events if we have java or node Js (which has one of the best library for push Notifications).
  • Microservices:- The word micro-services is in itself is says a lot and if we add another term 'Serverless' to it. Writing all the HTTPs application with a serverless function just Imagine! Yes, the elasticity we usually talk about in our small applications. Yes, we can manage these small apps for our Dev teams easily. 
All of these information can be found on Developer Key Note

As a developer, for me these are very exciting times to move ahead in career and learn what is all happening in development. 

I seriously think Salesforce has opened gates for us to learn more and develop the applications in the most standard way for our business. 

With note I would love to end this post, and a promise to keep sharing, demystifying and learning more about Evergreen functions., till then keep learning :) and coding :).


Note:- This is just an introductory post for Evergreen functions.

Cheers, 

Merry Christmas








Wednesday, 24 April 2019

IOT+Salesforce - Raspberry pie(Introduction) with Salesforce

Hi Folks,

I have taken a round of the sun and I reach here. Kidding! its more than 12 months I have written any blog. So here we go.

IOT- Salesforce + Raspberry pie


Internet of things (IOT) is going to be most talked and hyped topic this year . WHAT! Am I sounding like a visionary LOL :P. 

Lets get to the business. Internet of things in simple terms everything you see around will be going to be connected to internet. Yes, but how salesforce is looking at this currently, lets have a look. 

I am going to share a video in this one , actually series of videos from now on. 







Happy coding !! 

Note :- Its just and introductional video. I ll be soon coming up with end to end blog.






Tuesday, 13 March 2018

Lightning Best Practice to Access Data for Increasing performance of Application

Hi Folks,

Lightning Platform is the new buzz word. Lets talk about its best practice in a bit more detail.

My upcoming blogs will be on lightning best practice and will share my experience and findings.  Now, lets jump to main topic.


Data Access

In Lightning, accessing data is very easy as we have our super hero aura framework that does the magic. Many of the developers are stuck by the performance of the application. If not then sometimes client comes back to us and complaining about performance. 

For all these issues we have an old remedy but in new style. Word is CACHING! CACHING!. 

Ways to do Caching in lightning components:-

Caching in lightning is done by unique way . You dont have to write a full code for caching or to do something at browser level . 

action.setStorable();

({
    myAction : function(component, event, helper) {
        var action = component.get("c.getAccounts"); 
        //alert('startTime'+startTime);
        action.setStorable();
        action.setCallback(this, function(actionResult) {
            
            var state = actionResult.getState();
            if (state === "SUCCESS") {
                console.log("time taken to load in ms ", 
                            
                            performance.now()- startTime);
                        component.set('v.childRecords', actionResult.getReturnValue());

                var state = actionResult.getState();
            
            
        });
        var startTime = performance.now();
        $A.enqueueAction(action);
    }
})


This function does every thing you need to cache your data for caching. Lets take an example. 

I have a component in which I have display more than 1000 records in my component and that on press of button.

In my demo below, when action calls the server it takes around 500 ms and when clicked second time it takes around 2 ms. This is how you can cache the data without calling the server. This is the magic being handled by aura framework.



Watch the demo below:-



#Salesforce #Lightning #SetStorable #BestPractices #caching #cache


Thanks
Happy Coding :) :)



Friday, 22 December 2017

Animated Lightning Progress Bar Based on Input

Hi Folks,

Its all Lightning Now!

I was looking at Lightning Design System, it is the coolest, it struck my eye to Progress  Bar. So I thought to play around little bit with it.
Although, there are numerous other blogs available for the same, thought to share the same for beginners.

So lets get started...

Lightning Design System(LDS) has very good out of box classes and CSS written for us which we can directly consume in our code.

Lightning Progress Bar

Lets take input to complete the progress bar in percentage. Lets take this step by step:-

1. Below is the code for Component or app.
      I have added the code in app . you can add that code in a component also.

<aura:application extends="force:slds">
<!-- <AnkushTest:ProgressBarComponent />-->
           
    <aura:attribute name="value" type="Integer" default="0" />
    <aura:attribute name="inputVal" type="Integer" default="0" />
    <aura:attribute name="timeout" type="object" />
    <!-- ==============Using Lightning Progress bar tag  ==================   -->
    <div class="slds-progress-bar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="25" role="progressbar">
     <lightning:progressBar value="{!v.value}" />
    </div>
   
    <!-- ==============Using Lightning Design System ==================   --> 

    <div class="slds-m-around_small">
       
        <div class="slds-m-bottom_large">
            <label>Type the value : <ui:inputNumber  change="{!c.onChanged}" /></label>
        </div>
        <div>
            <div style="width:50%" class="slds-progress-bar slds-progress-bar_circular slds-progress-bar_large"
                 aria-valuemin="0" aria-valuemax="100" aria-valuenow="{!v.value}" role="progressbar">
                <span class="slds-progress-bar__value" style="{! 'width:  ' + v.value + '%;'}">
                    <span class="slds-assistive-text">{!'Progressing Value : ' + v.value + '%'}</span>
                </span>
                <div class="slds-text-align--center"><ui:outputNumber value="{!v.value}"/>
                    <ui:outputNumber value="100"/>
                    </div>
            </div>
        </div>
    </div>
    
    
   <style>
     .slds-progress-bar__value{
         background: green !important;
        }
    </style>
</aura:application>

Step By Step Explnation:-

There are two ways you can make progress bar
   A. By Using <lightning:progressBar> tag: It is a standard tag which renders as a horizontal bar. It        has various attributes which you can find easily on <lightning:progressBar>
  B.  Another way is by using Progress Bar .


2. We need to take input from user to make it animated i.e we need to keep refreshing the component or app after every nth sec to make it animated. For the same I have added that code in Helper.js


({
    Onchange : function(cmp, ev) {
       
        var currentValue=cmp.get('v.value');
        var finalValue=cmp.get('v.inputVal');
        var increment=1;
        if (finalValue<currentValue) {
            increment=-1; // in case the value needs to decreased if the value entered was less thn the initial value
        }
      
        var timeout = window.setInterval($A.getCallback(function() { // calling the function every n seconds
           
                var value=cmp.get('v.value');
                value+=increment; // Incrementing the value till it reaches the input value
                if (value==finalValue) {
                    window.clearInterval(cmp.get('v.timeout'));
                    cmp.set('v.timeout', null);
                }
                cmp.set('v.value', value); // set the incremented value to component 
            
        }), 200);
        cmp.set('v.timeout', timeout);
        
    }
})
In above code, the if loop inside window.setinterval makes sure that till the input value is equal to desired value this refresh should happen. once it value is achieved then set clear your interval.

3. Controller code :-

({
    onChanged : function(component, event, helper) {
        helper.Onchange(component, event);
    }
})




Just try it out , it will be fun ..

In case you face any issue just drop me message or mail.

Cheers!!
Happy Coding !



Tuesday, 14 November 2017

How to create Dependent Picklist Using lightning Component and change background Color

Hi Folks,

As it is rightly said "The more you share , the more you learn". With this thought I ll keep exploring and ll keep sharing some basic stuff for lightning beginners.

Lets jump to scenario first:-

We need to create Dependent Picklist using Lightning Component, Sounds very easy isn't it . Hold on there is a twist to it we need to change the background color based on selected value.

Lets get started:-
Firstly , we need to have attribute to hold parent picklist value i.e

<aura:attribute name="pOptions" type="List"/>
Step 2 :-
<lightning:select name="pPicklist"  label="Alphabets" aura:id="pPicklistId" onchange="{!c.onPickchange}">
            <option value="">None</option>
            <aura:iteration items="{!v.pOptions}" var="p">
                <option value="{!p.value}">{!p.text}</option>
            </aura:iteration>
        </lightning:select>
This actually is creating  the parent picklist which is a list of alphabets. It has a onchange controller.


 myAction : function(component, event, helper) {
        var pVals = [
            {text:"A", value:"A"},
            {text:"B", value:"B"}
        ];
        var pValsColor = [
            {text:"White", value:"White"},
            {text:"blue", value:"blue"}
        ];
        var cVals = {
            "A":[
                {text:"A1", value:"A1"},
                //{text:"Choose Color", value:"Choose Color"}
            ],
                "B":[
                {text:"B1", value:"B1"},
                {text:"Choose Color", value:"Choose Color"}
            ]
        };
        component.set('v.pOptions',pVals);
        component.set('v.DepenedentObject',cVals);
        component.set('v.cColor',pValsColor)
    },
This controller is  called whenever the page is loaded and it sets the initial values to picklist.


Step 3:-
Now, we have to create child picklist values.

<div class="slds-form--stacked">
            <lightning:select name="cPicklist"  label="Childs" aura:id="cPicklist" disabled="{!v.disabledPick}" onchange="{!c.myColor}">
                <option value="">None</option>
                <aura:iteration items="{!v.cOptions}" var="k">
                    <option value="{!k.value}">{!k.text}</option>
                </aura:iteration>
            </lightning:select>
        </div>
            <div class="slds-form--stacked">
        <lightning:select name="cPicklistColor"  label="Color" aura:id="cPicklistColor" onchange="{!c.myColor}" disabled="{!v.disabledColorPick}">
            <option value="">None</option>
            <aura:iteration items="{!v.cColor}" var="k">
                <option value="{!k.value}">{!k.text}</option>
            </aura:iteration>
        </lightning:select>
This above code is creating the child picklist and also has onchange.





Here is full code for you below to test and try:- 



<aura:component >
    <ltng:require styles="{!$Resource.slds232 + '/assets/styles/salesforce-lightning-design-system.css'}"/>
    <aura:attribute name="pOptions" type="List"/>
    <aura:attribute name="cOptions" type="List"/>
    <aura:attribute name="selectedRedColor" type="Boolean" default="false"/>
    <aura:attribute name="cColor" type="List"/>
    <aura:attribute name="DepenedentObject" type="object"/>
    <aura:attribute name="disabledPick" type="Boolean" default="true"/>
    <aura:attribute name="disabledColorPick" type="Boolean" default="true"/>
    <aura:handler name="init" value="{!this}" action="{!c.myAction}"/>
    
    <div class="slds-align_absolute-center">
        <lightning:select name="pPicklist"  label="Alphabets" aura:id="pPicklistId" onchange="{!c.onPickchange}">
            <option value="">None</option>
            <aura:iteration items="{!v.pOptions}" var="p">
                <option value="{!p.value}">{!p.text}</option>
            </aura:iteration>
        </lightning:select>
        <div class="slds-form--stacked">
            <lightning:select name="cPicklist"  label="Childs" aura:id="cPicklist" disabled="{!v.disabledPick}" onchange="{!c.myColor}">
                <option value="">None</option>
                <aura:iteration items="{!v.cOptions}" var="k">
                    <option value="{!k.value}">{!k.text}</option>
                </aura:iteration>
            </lightning:select>
        </div>
            <div class="slds-form--stacked">
        <lightning:select name="cPicklistColor"  label="Color" aura:id="cPicklistColor" onchange="{!c.myColor}" disabled="{!v.disabledColorPick}">
            <option value="">None</option>
            <aura:iteration items="{!v.cColor}" var="k">
                <option value="{!k.value}">{!k.text}</option>
            </aura:iteration>
        </lightning:select>
    </div>
    <div class="slds-is-relatived" style="position: absolute; top: 1rem; left: 1rem;">
        <aura:if isTrue="{!v.selectedRedColor}">
            <style >
                html{
                background-color: blue ;
                }
                
            </style>
            <p class="slds-text-color_default"> Show Color :-  I am Blue  </p>
        </aura:if>
        
    </div>
    </div>

</aura:component>

Lets now take a look at controller :-

({
    myAction : function(component, event, helper) {
        var pVals = [
            {text:"A", value:"A"},
            {text:"B", value:"B"}
        ];
        var pValsColor = [
            {text:"White", value:"White"},
            {text:"blue", value:"blue"}
        ];
        var cVals = {
            "A":[
                {text:"A1", value:"A1"},
                //{text:"Choose Color", value:"Choose Color"}
            ],
                "B":[
                {text:"B1", value:"B1"},
                {text:"Choose Color", value:"Choose Color"}
            ]
        };
        component.set('v.pOptions',pVals);
        component.set('v.DepenedentObject',cVals);
        component.set('v.cColor',pValsColor)
    },
    onPickchange : function(component, event, helper) {
        var cValues = component.find('pPicklistId').get('v.value');
        component.set('v.cOptions',component.get('v.DepenedentObject')[cValues]);
        //alert(cValues);
        console.log(component.get('v.DepenedentObject')[cValues]);
        if(cValues != '')
            component.set('v.disabledPick',false);
        else
            component.set('v.disabledPick',true);
    },
    
    myColor : function(component, event, helper) {
        //alert('function called');
        var cValuesColor = component.find('cPicklist').get('v.value');
        var sColor = component.find('cPicklistColor').get('v.value');
        //alert(sColor);
        if(sColor == 'blue'){
           // alert(sColor);
            component.set('v.selectedRedColor',true);
        }
        else{
            //alert(sColor);
            component.set('v.selectedRedColor',false);
        }
        if(cValuesColor == 'Choose Color')
            component.set('v.disabledColorPick',false);
        else if(cValuesColor != 'Choose Color'){
            component.set('v.disabledColorPick',true);
        }
    }
    
})

Click below to see 
Working demo on You tube

In case you find any issue just drop me a mail on ankushsalesforce@gmail.com


Happy Codding
Cheers !!

Thanks
Ankush


Sunday, 5 November 2017

How To show picklist on Visualforce using Lightning Components and apex class

Hi Folks,

Lightning! Is it..

I have a requirement for you and that is very basic for new beginners who wants to learn lightning.

Requirement:-

To show picklist on visualforce using lightning component and also print the selected value. 

Lets start with creating the component . We need to have a component , a controller and lightning out app.
In component, we will be using two attributes to which one will contain the selected value and another attribute which will contain the picklist values.

Also we will have a client side controller that will be called on load of component and whenever there is change in picklist value selection.

Component code snippet below:-


<aura:component implements="flexipage:availableForAllPageTypes" access="global">
    <ltng:require styles="{!$Resource.slds232 + '/assets/styles/salesforce-lightning-design-system.css'}"/>
    <aura:attribute name="mySelectedText" type="String" default="some string"/>
    <aura:attribute name="contactLevel" type="set" default="test" />
    <aura:handler name="init" value="{!this}" action="{!c.onSelectChange}"/>
  <div>
    <ui:inputSelect aura:id="levels" label="Contact Levels" change="{!c.onSelectChange}">
        <aura:iteration items="{!v.contactLevel}" var="level">
             <ui:inputSelectOption text="{!level}" label="{!level}"/>
        </aura:iteration>
    </ui:inputSelect>
  </div>
    <div>
        Selected value is :----  {!v.mySelectedText}
    </div>
</aura:component>

Visualforce page code snippet

<apex:page controller="linkforLightning">
<apex:includeLightning />
<apex:outputPanel id="twest" rendered="true">

 <div style="width:100%;height:100px;" id="Containers" />

 <script>
 $Lightning.use("AnkushTest:onSelectChange", function() {
 $Lightning.createComponent("AnkushTest:onSelectPicklist",
 {  
     contactLevel:"{!listOfInteger}"
  
 },
 "Containers",
 function(cmp) {
 console.log('Component created');
 });
 });
 </script>
 </apex:outputPanel>
</apex:page>

Controller.js :-


({
 onSelectChange : function(component, event, helper) {
    var selected = component.find("levels").get("v.value");
        alert('Selected Value is '+selected);
        
      
    component.set("v.mySelectedText",selected);
        
}
})
Lightning App

<aura:application access="GLOBAL"  extends="ltng:outApp">
    <aura:dependency resource="AnkushTest:OnSelectPickList" />
</aura:application>

This how it will be rendered







Sunday, 15 October 2017

Simple Way to Override An object new button in Salesforce!

Hi Folks,

How are you doing? Obviously fine :P.

I have been getting active back socially of course for Salesforce. I saw a problem statement on overrding a new button on standard salesforce object.
I am not sharing something new, it is just sharing some cool out of box functionalities of salesforce for overrding the a new button .

NO intensive code. 


Are you aware of action attribute of visualforce, URLFOR and $Action then I believe you will save your lot of time in visualforce coding.

Lets say you want a return Url to be lead view page. Now, instead of coding and having apex class you can actually make it easy by just adding this in action attribute.


<apex:page standardController="Lead" 
  action="{!URLFOR($Action.Lead.New,$ObjectType.Lead,[lea3=$User.companyname,retURL=$ObjectType.Lead.keyprefix],true)}">
</apex:page>


Yes, its very easy to override and also to make your return URL of your choice. In case you stuck in any error, need not say just message me. We will Demitsify it together and spread learning.


Happy Coding :)

Thanks
Ankush


Saturday, 12 August 2017

How to Build Alert! on visualforce Page Using Lightning Component Salesforce

Hi Folks,

Its the high time we get our hands dirty on LIGHTNING. We are getting lots of requirement on lightning day by day. In market there is a huge demand for Lightning Developers.

Obviously, every one is going mobile now a days and want one solution with better performance in salesforce. #LightningIsTheWayToGo. 

Today I ll be sharing some stuff i.e  most used component on internet among Developers that is 'ALERT !'

Lets get Started folks....


Requirement Analysis:-

I was asked to build, actually no one asked me it got boomed in my head ,  Alert! as Lightning Component. This lightning component should be such that we can use it in our visualforce pages wherever we want to show an alert.

our Component:-

First create a component named GlobalAlert.

Below is the code snippet for the same.

     <!--Global Alert-->
<aura:component implements="flexipage:availableForAllPageTypes" access="global">
    <ltng:require styles="{!$Resource.slds232 + '/assets/styles/salesforce-lightning-design-system.css'}"/>
    <aura:attribute name="Title" type="String" default="You Encountered an Error!!  " />
    <aura:attribute name="Click" type="String" default="  Please Click Here" />
    <aura:attribute name="Link" type="String" default="  Please Click Here" />
    
<div class="slds-notify slds-notify_alert slds-theme_alert-texture slds-theme_error" role="alert">
                      <span class="slds-assistive-text"> </span>
                      <span class="slds-icon_container slds-icon-utility-ban slds-m-right_x-small" title="Description of icon when needed">
             
              <lightning:icon iconName="utility:error" variant="error" />
        
          </span>
          <h2>{!v.Title} <a href="{!v.Link}">{!v.Click}</a></h2>
          <button class="slds-button slds-button_icon slds-notify__close slds-button_icon-inverse" title="Close">
              <lightning:icon iconName="utility:error" variant="error" />
              
            <span class="slds-assistive-text">Close</span>
          </button>
</div>
  
</aura:component>
Explanation of above Code line by line :-

Please visit this link. It is the Lightning Design System It has all the libraries for the component which are used mostly in development.

You can directly consume these CSS files into you Lightning App.


 <ltng:require styles="{!$Resource.slds232 + '/assets/styles/salesforce-lightning-design-system.css'}"/>
Above line is a standard tag of lightning in its style attribute I have added my CSS from lds (Lightning Design System).


<aura:attribute name="Title" type="String" default="You Encountered an Error!!  " />
    <aura:attribute name="Click" type="String" default="  Please Click Here" />
    <aura:attribute name="Link" type="String" default="  Please Click Here" />
In this above Code , I have added Aura attribute to pass as a parameter from my VF page.


<div class="slds-notify slds-notify_alert slds-theme_alert-texture slds-theme_error" role="alert">
                      <span class="slds-assistive-text"> </span>
                      <span class="slds-icon_container slds-icon-utility-ban slds-m-right_x-small" title="Description of icon when needed">
             
              <lightning:icon iconName="utility:error" variant="error" />
        
          </span>
          <h2>{!v.Title} <a href="{!v.Link}">{!v.Click}</a></h2>
          <button class="slds-button slds-button_icon slds-notify__close slds-button_icon-inverse" title="Close">
              <lightning:icon iconName="utility:error" variant="error" />
              
            <span class="slds-assistive-text">Close</span>
          </button>
</div>
 In the above code, this copied from lightning css for alert. Just remember you need to use <lightning:icon> tag as it is a alternate tag for <svg>



Visualforce Page:-




<apex:page controller="linkforLightning">
<apex:includeLightning />
<apex:outputPanel id="twest" rendered="true">

 <div style="width:100%;height:100px;" id="Containers" />

 <script>
 $Lightning.use("AnkushTest:DemoLightningContApp", function() {
 $Lightning.createComponent("AnkushTest:GlobalAlert",
 { Link:"{!link}"
  
 },
 "Containers",
 function(cmp) {
 console.log('Component created');
 });
 });
 </script>
 </apex:outputPanel>
</apex:page>

To call Lighning Component I have to add a function in a script tag. 



$Lightning.use("AnkushTest:DemoLightningContApp", function() {
 $Lightning.createComponent("AnkushTest:GlobalAlert",
 { Link:"{!link}"

Above code creates and initializes the lightning component by using $lightning.use("You component name",function()).

link is my attribute through whoch I can dynamically create an alert .

This Way you can reuse your alert component in dfiferent visualforce pages.




Happy Lightning!!

😊

Sunday, 16 July 2017

Not rendering Clickable Link on Visualforce Page in apex:pageMessages

Hi Folks,

I was trying to cover a scenario I need to show a clickable link on visualforce page on some error condition with a navigating back to original record. 

I know we have in built standard tag i.e 

apex:pageMessages


Lets say you want to show a clickable message that needs to be redirected to some other link . This navigation can be done within or outside salesforce. So, generally we use the below line to show the clickable link. 

           String orderId = System.URL.getSalesforceBaseUrl().toExternalForm();
            String err = '<b><a href="' + orderId +'/'+OrderId+ '">Click Here to Continue  here</a>.';
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,err));

But some how it was showing me on the page as like this "'<b><a href="' + orderId +'/'+OrderId+ '">Click Here to Continue here"

But then I checked that there is an attribute i.e Escape

A Boolean value that specifies whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If you do not specify escape="false", the character escape sequence displays as written. Be aware that setting this value to "false" may be a security risk because it allows arbitrary content, including JavaScript, that could be used in a malicious manner.

If I make Esacape = false then it renders as link. 

Thanks
Ankush


Happy Coding 😉




Friday, 31 March 2017

Updates From Spring 17 Release Notes -Key Points to Remember

Hi Folks,

It's very much hot outside , as summers are already up. I was notified for my maintenance exam and thought to go through the release notes of Spring' 17.

Salesforce is ramping up pretty fast with all its new features and products. As a developer need to catch up with all the updates.

Thought to share the updates with all of you.

Here are the few key points that may help you for Spring Release:-

  1.  Global Action Menu :- 

    Global Actions are another awesome feature that has some updates like its capabilities to :-
    • Take notes
    • Launch Visualforce
    • Create records          
     2.   Favorites in Lightning Experience:-
    • Only User Can edit his or Favourites.
     3. If an old post with a file is shared in Lightning Experience, Then how is the new file in the          newly shared post will look like
 
    • A link to the file is shared and it is available as a link.
     4. Merged in Lightning Experience:-

    • Only 3 Records can be merged at once.
     5.  Predefined values for send email action:-

    • TO
    • CC
    • BCC
      6.  Lightning Record Pages can be assigned to:-
    • Record types
    • Apps
    • Profiles
       7. Three types of content can shortcuts be created for using Favorites:-

    •  Dashboards
    • Record home pages
    • Chatter groups
        8.   Feature that enables creating, updating and deleting records in other Salesforce orgs:-

    • Salesforce Connect Cross-Org Adapter.
       9.  An image included in the Salesforce Lightning Design System from a Visualforce page ,                Mark ups for the same :-
    • <apex:slds>
    • $Asset
      10.  Capabilities Of Global Actions Menu:-


  • Launch a custom Visualforce Page.
      • Launch a custom Canvas App.
      • Launch a custom Lightning Component.
            11.  Detailed information about the status of an Apex batch job:- 

      • Elapsed time
      • Submitted date
            12.  component type will display the details of the parent Account from a custom Lightning                       record page for the Contact object  :-


      • Related record component









    Thursday, 26 January 2017

    Simple Pagination In salesforce

    Hi Folks,

    Its been long since I have written any blog. Please welcome me :P.

    Ok. lets roll to business. I ll be sharing simple way of Pagination in salesforce. Lemme first Explain you the three variable I have used here in my Apex class :-

    totalRecs = 0;
    OffsetSize = 0;
    LimitSize= 10;

    totalRecs is used for tracking the total number of records that have fetched. So that I can deduct it fro the total number of records that have been shon so far in previous pages.

    OffsetSize is used for showing the rest of the records on the current page number.

    Limitsize is used for declaring the count of records that will be shown on every page.

    So guys dnt worry here is the code:-



    
           public class Pagination
    {
            private integer totalRecs = 0;
            private integer OffsetSize = 0;
            private integer LimitSize= 10;
            public Pagination()
            {
                totalRecs = [select count() from account];
            }
            public List<account> getacclist()
            {
                List<account> acc = Database.Query('SELECT Name, website, AnnualRevenue, description, Type FROM account LIMIT :LimitSize OFFSET :OffsetSize');
                System.debug('Values are ' + acc);
                return acc;
            }
            public void FirstPage()
            {
                OffsetSize = 0;
            }
            public void previous()
            {
                OffsetSize = OffsetSize - LimitSize;
            }public void next()
            {
                OffsetSize = OffsetSize + LimitSize;
            
            }
            public void LastPage()
            {
                OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
            }
            public boolean getprev()
            {
            if(OffsetSize == 0)
                return true;
                else
                return false;
            }
            public boolean getnxt()
            {
                if((OffsetSize + LimitSize) > totalRecs)
                return true;
                else
                    return false;
            }
    }



    
           <apex:page controller="Pagination" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageBlock id="details">
            <apex:pageblockTable value="{!acclist}" var="acc">
                <apex:column value="{!acc.Name}"/>
                <apex:column value="{!acc.website}"/>
                <apex:column value="{!acc.AnnualRevenue}"/>
                <apex:column value="{!acc.Description}"/>
                <apex:column value="{!acc.Type}"/>
        </apex:pageblockTable>
    <apex:pageblockButtons >
        <apex:commandButton value="First Page" rerender="details" action="{!FirstPage}" disabled="{!prev}"/>
        <apex:commandButton value="Previous" rerender="details" action="{!previous}" disabled="{!prev}"/>
        <apex:commandButton value="Next" rerender="details" action="{!next}" disabled="{!nxt}"/>
        <apex:commandButton value="Last Page" rerender="details" action="{!LastPage}" disabled="{!nxt}"/>
    </apex:pageblockButtons>
    </apex:pageBlock>
    </apex:form></apex:page>



    Thanks
    Happy Coding !!

    Cheers!!

    Sunday, 1 November 2015

    Blank Values in Merge Fields HTML template sending mail through Apex code Salesforce!

    Hi Folks,

    Its been ages since am here. I switched to a new company got busy there. Anyways,,, Lets get started with another requirement and isssue.


    Issue:- I was unable to get values in merge fields from the template that I have qurried. 




    
    
    
           
    So if we want to use standard email template then we have to use setWhatId to specify the record for which the merge fields should calculate . But the limlitation here is if we have setTargetObjectId which should be Id of  user , contact or a lead. This will not work if we user Id as a setTargetObject Id. It needs to be a contact Id . Otherwise, email which you will receive will have blank value. 

    Cheers
    Ankush







    Saturday, 28 March 2015

    How to Add rows in a visualforce page ?

    Hi guys,

    Last month I got an opportunity to work on very much exploited functionality :P ::P i.e Adding rows in visual force page. Although, you ll find numerous of example on Google.

    There are many simple examples on internet.

    Scenario:- On a visual force page , whenever the page loads it should have five rows a default of contact fields. Also i should have a button of adding rows i.e 5 on click of that button .

    Lemme share you the result first (See the screen shot below)



    Solution:-  Let me add the code and ll explain you section wise. Lets start with visual force page first.

    <apex:page StandardController="Contact" extensions="CreateContctss">
        <apex:form >
        <!--<apex:pageMessage strength="3"  />-->
        
        <apex:outputPanel id="OutMessage">
               <apex:pageMessages rendered="{!errorMessage}"/> 
        </apex:outputPanel> 
        <apex:outputPanel id="addrows">
            <apex:pageBlock >
    
              <table>
                <tr>
                    <td>First Name</td>
                    <td>Last Name</td>
                    <td>Email</td>
                </tr>
                    <apex:repeat value="{!contactList}" var="con">
                 <tr>
                        <td><apex:inputtext value="{!con.wrapperContact.Firstname}" id="idOFFirstname"/></td>
                        <td><apex:inputtext value="{!con.wrapperContact.LastName}" id="theValue"/></td>                    
                        <td><apex:inputtext value="{!con.wrapperContact.email}" id="idOFEmail"/></td>
                    </tr>
                </apex:repeat>
            </table>
                    <apex:pageblockButtons >
                        <apex:commandButton value="Add Contact" action="{!redirectPage}" />
                        <apex:commandButton value="Add rows" action="{!AddRows}" reRender="addrows"/>
    
                    </apex:pageblockButtons>
            </apex:pageBlock>
          </apex:outputPanel>  
        </apex:form>
    </apex:page>


    So, we have to use the apex:repeat tag. To Iterate over the wrappercontact list . So that it should repeat the list 5 times whenever the page is loaded.
    We have a button Add rows which adds five more similar rows on button pressed.

    i am using the standard controller i. Contact and its extension for enhancing its functionality.

    So, lets jump to code .

    public with sharing class CreateContctss {
       public list<wrapperContact> wrapperContList{get; set;}
       public boolean errorMessage{get;set;}
       public boolean recordInserted{get;set;}
       
       Id acoountID = apexpages.currentpage().getparameters().get('IdOfAccount');
       Id newId= apexpages.currentpage().getparameters().get('newid');
       
       public list<Contact> listOfwrappedContact = new list<Contact>();
       
       //public List<wrapperContact> wrapperContList= new List<wrapperContact>();
       public list<wrapperContact> contactList{ get{
                if(wrapperContList == null){
                   system.debug('wrapperContlist=='+wrapperContList);
                   wrapperContList = new list<wrapperContact>();
                   system.debug('wrapperContlist=='+wrapperContList);
                    System.debug('hello.....'+wrapperContList);        
                    for(integer i= 1; i<6; i++){
                        if(newId == null){
                            wrapperContList.add(new wrapperContact(new contact(AccountID = acoountID)));
                            System.debug('newId =='+newId);
                            system.debug('wrapperContlist=='+wrapperContList);
                            }else{
                            System.debug('newId =='+newId);
                            system.debug('wrapperContlist=='+wrapperContList);
                                wrapperContList.add(new wrapperContact(new contact(AccountID = newId)));
                            }
                        }
                    }
                    return wrapperContList ;
                    }
                    set;}
          
       /* public list<Contact> contactList {get{
                if(contactList == null){
                    contactList = new list<Contact>();
                    System.debug('hello.....'+Contactlist);        
                    for(integer i= 1; i<6; i++){
                        if(newId == null){
                        contactList.add(new Contact(AccountID = acoountID ));
                        System.debug('newId =='+newId);
                            }else{
                            System.debug('newId =='+newId);
                                contactList.add(new Contact(AccountID = newId));
                            }
                        }
                    }
                    return contactlist;
                    }
                    set;}*/
        public CreateContctss(ApexPages.StandardController controller) {
            errorMessage = false;
            recordInserted= false;
            ///wrapperContList= null;
        }
    
        
        private void insertContact(){
            listOfwrappedContact.clear();// which is better approach 
            for(wrapperContact con : wrapperContList){
                listOfwrappedContact.add(con.wrapperContact);
            }
            string error;  
            system.debug('wrapperContlist=='+wrapperContList);
            Database.SaveResult[] srList = Database.insert(listOfwrappedContact , false); // used database.save result because if there are more required fields in future then it would be easier for us to handle 
               System.debug(srList);
               for (Database.SaveResult sr : srList) {
                    if (sr.isSuccess()) {
                        // Operation was successful, so get the ID of the record that was processed
                        System.debug('Successfully inserted account. Account ID: ' + sr.getId());
                        recordInserted= true;
                    }
                    else {
                    // Operation failed, so get all errors                
                    for(Database.Error err : sr.getErrors()) {
                        System.debug('The following error has occurred.');                    
                        System.debug(err.getStatusCode() + ': ' + err.getMessage());
                        System.debug('Account fields that affected this error: ' + err.getFields());
                        error = + err.getMessage();
                        errorMessage = true;
                        }
                    }
               }
                   /* ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please fill at least one Last name ');
                    ApexPages.addMessage(myMsg);*/
           }    
        public PageReference redirectPage(){
        try{
         insertContact();
         }catch(exception e){
                     ApexPages.AddMessages(e);
                     return null;
         }
         for(wrapperContact con : wrapperContList){
             system.debug('LastName1'+con.wrapperContact.LastName);
             system.debug('Email1'+con.wrapperContact.Email);
             Boolean result;
             Boolean emailerror;
             Boolean LastNameerror;
             if(con.wrapperContact.Email != ''){
                String emailRegEx = '[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\*\\/\\=\\?\\^\\_\\+\\-\\`\\{\\|\\}\\~\'._%+-]+@[a-zA-Z0-9\\-.-]+\\.[a-zA-Z]+';
                Pattern MyPattern = Pattern.compile(emailRegex);
                Matcher MyMatcher = MyPattern.matcher(con.wrapperContact.email);
                result = MyMatcher.matches();
                System.debug('Result'+result);
                }
            
             if(result == false){
                  ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please check email format');
                  ApexPages.addMessage(myMsg);
                 emailerror = true;
             }
             System.debug(con.wrapperContact.lastname.length());
             if(con.wrapperContact.lastname.length() > 80){
             system.debug('more than 80');
                  ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Last name cannot be too large ');
                  ApexPages.addMessage(myMsg);         
                  //return null;
                  }
                  
             if(con.wrapperContact.lastName == ''){
                if( recordInserted == false){   
             
              System.debug(con.wrapperContact.lastName);
              ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please fill at least one Last name ');
              ApexPages.addMessage(myMsg);
              LastNameerror= true;
                  
                    }
             }
             if(LastNameerror== true || emailerror == true){return null;}
         }
         if(newId == null){
             pagereference prt= new pagereference('/'+acoountID).setRedirect(true);
             return prt;
        }else{
            pagereference prr= new pagereference('/'+newid).setRedirect(true);
            return prr;
            }  
        }
    
                Public pagereference  addRows(){
                    //wrapperContList = new list<wrapperContact>();
                    for(Integer i=0;i<5;i++){
                      if(newId == null){
                        wrapperContList.add(new wrapperContact(new contact(AccountID = acoountID)));
                        System.debug('newId =='+newId);
                        system.debug('wrapperContlist=='+wrapperContList);
                            }else{
                                System.debug('newId =='+newId);
                                system.debug('wrapperContlist=='+wrapperContList);
                                wrapperContList.add(new wrapperContact(new contact(AccountID = newId)));
                            }
                        }
                return null;
            }
        
        public class wrapperContact{
            public Contact wrapperContact{get;set;}
            public wrapperContact(contact c){
                wrapperContact = c;
            }
        }
    }

    I have to use wrapper class to contain it as one entity. Because every time I click on Add rows button I need to do some process as a whole.

    ignore apex.pages.currentpage().get('id') as of now.

    Your focus area should be only Add rows method . In this, we have to iterate over the wrappercontlist. and add them to visual force page.

    Important point to note here is rendering . You need to use output panel id . to reRender on page .

    Keep Learning Salesforce

    Thanks
    Cheers
    ankushsalesforce@gmail.com



    Saturday, 14 March 2015

    How To Deactivate the trigger in Production Org without modifying it?

    Hi Guys,

    I have a requirement that I need to deactivate a trigger without modifying it in production. Is there any magic wand to do this. Kidding, isn't. it :P

    Obviously this is not my Idea , a friend of my told me how to do this so thought to share with all of you.

    Solution:- 

    Have your ever heard of custom setting. yes, In custom setting you need to make a check box field. name it switch.

    Then in your trigger you need to querry the this custom  setting field and just check whether it is true or false. If it is true then run your logic otherwise do nothing.

    Lemme  share the code snippet with you.

    Trigger SwitchTrigger on Account (<event>){
    if(Switch__c == true){
    Your   *** Logic
    }
    }

    So , when ever you want to deactivate the trigger in production just go to custom setting and uncheck the check box.


    keep learning Salesforce
    thanks
    ankushsalesforce@gmail.com


    Sunday, 1 March 2015

    how to use param tag in visualforce?

    Hi guys,

    Few days back , I was working on apex param tag. I had an requirement to insert a contact under the account I have clicked from different page. I don't have to provide the definition. to this as you know it is there on the internet .

    Scenario: -  I have a custom page where I have the table which displays the account as command link. On clicking  any of the record of account should take me to a custom page where I can create contact. Contact which gets inserted should get associated to the account I clicked on.

    Solution:-  We have to use the apex param tag in our page and have to send the ID to the url, when redirecting to to our custom contact page.

    Lemme walk you through the code snippet:-

    <apex:pageBlockTable value="{!Accounts}" var="item">
                               <apex:column headervalue="Account Name">
                                    <apex:commandLink action="{!redirectPage}">
                                          <apex:param name="IdOfAccount" value="{!item.id}"/>
                                          {!item.Name}
                                    </apex:commandLink>
                               </apex:column>
      </apex:pageBlockTable>

    As you can see in the command link tag  have used apex param. In the param tag I have used name attribute and i have assigned it a name as 'IdOFAccount' , through this am sending the Id of account. which I have selected.

    Lemme show How I am catching this parameter in code and redirecting to custom contact page.


        public PageReference redirectPage(){
            ID = apexpages.currentpage().getparameters().get('IdOfAccount');
            pagereference pr= new pagereference('/apex/CreateContac?IdOfAccount='+ID).setRedirect(true);
            return pr;
        }

    As in command link in action attribute I have mentioned redirectPage. In the instance of pageref I have redirected it to createContact page with IdOfaccount from my visualforce page.


    This How You can easily make the use of   Apex param tag.

    Soon, I ll be uploading a video of demo.

    cheers!

    #happyCoding
    ankushsalesforce@gmail.com


    Wednesday, 18 February 2015

    How to overide standard salesforce save button?

    Hi guys!

    Yesterday, I was working on overiding the standard save and cancel button. I know there are many blogs you ll find easily on google.

    Anyways, am just sharing just to add a simple way(I think , u may find more easier  :P:P) of overiding . Lets jump to scenario.

    Scenario:-  Say, I have a custom visualforce page abc and from there I have given a button on that page. When that button is pressed, it should take us to standard edit page of account. After clicking the save button it should take us to custom visualforce page. lets say to xyz page.



    So , you guys are aware of  URL parameters that are appended when you open standard detail page of account inedit mode it is like :-

    https://na15.salesforce.com/001/e?retURL=%2F001%2Fo

    So, what happen is after you fill the details. and hit save button. it takes you to the record itself . It is the standard salesforce  functionality.

    Lets see what these parameters are meant for:-

    1. 001 - it is id of account object.
    2. 001/e?-  It stands for edit mode .
    3. retURL - It is the url when you click the cancel button
    4. saveURL - It is the URL for landing page.

    So, my requirement is that I have to redirect from my custom visulforce page to account edit page.
    to do this - in your page refrnce method append this

    pagereference pr= new pagereference('/001/e?retURL=/apex/AccountSearch&saveURL=/apex/CreateContac').setRedirect(true);

    Thanks
    Ankush






    Sunday, 1 February 2015

    How salesforce matches Contact to the case when an email is received in Email-To-Case

    Hi Guys,

    I have been working on salesforce's Email to case Functionality since December. I cant say am perfect in it , but have got a good hold as of now.

    Let me just walk you through how salesforce Email-To-Case functionality works. Though , ll not brief here about setting email to case .

    So, when an customer sends an email to salesforce org. Then a case is created in the salesforce.

    Let say, You have a contact  with a name xyz and his email address is xyz@abc.com. So, when he ll send an email to raise a case, his case will be created and and his contact will be asscoiciatd  with this case.

    And how salesforce does this, all explationaltion is given here in salesforce know;ledge article.

    CLICK HERE.


    My AI Channel

    Hi Folks,  Its been a while posted any post on Salesforce. I feel like Salesforce can waith but new AI hype cant, need to go with the flow. ...