Thursday, December 31, 2015

Let's Celebrate New Year 2016

Wishing you a great, prosperous, blissful, healthy, bright, delightful, energetic and extremely Happy New Year 2016.


May the bad times you faced in the year 2015 be your stepping stones to success and may you be blessed with many happy moments in 2016. Happy New Year.



New Year is not about changing the dates but direction; it’s not about changing the calendar but commitment; it’s not about changing the actions but attitude. May each and every day of yours is renewed with lots of happiness and love. 

  

Once Again Wishing you a great, prosperous, blissful, healthy, bright, delightful, energetic and extremely Happy New Year 2016.

Enjoy...................!


Wednesday, December 30, 2015

How to show red asterisk symbol in place of red vertical bar for all inputFileds in visaulforce page

Basically whenever using Standard controller in a visual force page showing vertical red mark before all mandatory filed using <apex:inputFiled> is very easy because we can simply use required="true" attribute.Whenever user click on any action button on page it will check for all the mandatory field values and if any one or more filed value is not filled it will shown an error below each field like Error: You must enter a value.


Now my requirement here is I want to show red asterisk symbol in place of red vertical bar for all inputFileds in visaulforce page and I want to retain all the features of <apex:inputFiled> like checking for mandatory fields and displaying an error message as Error: You must enter a value.So in this post i'm going to show how to show red asterisk symbol in place of vertical bar.

Write a sample visual force to show vertical red bar
 <apex:page standardController="Account">  
  <apex:form >  
  <apex:pageBlock >  
   <apex:pageBlockSection title="Account Information" collapsible="true">  
    <apex:inputField value="{!account.name}" required="true"/>  
    <apex:inputField value="{!account.type}" required="true"/>  
    <apex:inputField value="{!account.Industry}" required="true"/>  
    <apex:inputField value="{!account.rating}" required="true"/>  
   </apex:pageBlockSection>  
   <apex:pageBlockSection title="Address" collapsible="true">  
    <apex:inputField value="{!account.Billingcity}" required="true"/>  
    <apex:inputField value="{!account.BillingState}" required="true"/>  
    <apex:inputField value="{!account.BillingCountry}" required="true"/>  
    <apex:inputField value="{!account.BillingPostalCode}" required="true"/>  
   </apex:pageBlockSection>  
   <apex:pageblockButtons ><apex:commandButton value="Save" action="{!save}"/></apex:pageblockButtons>  
  </apex:pageBlock>  
  </apex:form>  
 </apex:page>  

When you run the above page it will displays all input fields with vertical red var as shown below


















If you haven't filled any one mandatory fields and click on save it will throws error below the field


Workaround to show red asterisk symbol in place of red vertical bar for all inputFileds

Just we need to add below 2 lines of style snippet in visual force page to show red asterisk
 <style>  
    .bPageBlock .requiredInput .requiredBlock{background-color: #F6FBF6;}  
    .requiredInput .requiredBlock::before { display: block; content: "*"; font-size: 1.5em; font-weight: bold; color: #c00; margin-left: -4px; margin-top: -2px; } 
 </style>  

Complete visual force after adding the above style snippet is looks like below
 <apex:page standardController="Account">  
  <apex:form >  
  <apex:pageBlock >  
   <apex:pageBlockSection title="Account Information" collapsible="true">  
    <apex:inputField value="{!account.name}" required="true"/>  
    <apex:inputField value="{!account.type}" required="true"/>  
    <apex:inputField value="{!account.Industry}" required="true"/>  
    <apex:inputField value="{!account.rating}" required="true"/>  
   </apex:pageBlockSection>  
   <apex:pageBlockSection title="Address" collapsible="true">  
    <apex:inputField value="{!account.Billingcity}" required="true"/>  
    <apex:inputField value="{!account.BillingState}" required="true"/>  
    <apex:inputField value="{!account.BillingCountry}" required="true"/>  
    <apex:inputField value="{!account.BillingPostalCode}" required="true"/>  
   </apex:pageBlockSection>  
   <apex:pageblockButtons ><apex:commandButton value="Save" action="{!save}"/></apex:pageblockButtons>  
  </apex:pageBlock>  
  <style>  
    .bPageBlock .requiredInput .requiredBlock{background-color: #F6FBF6;}  
    .requiredInput .requiredBlock::before { display: block; content: "*"; font-size: 1.5em; font-weight: bold; color: #c00; margin-left: -4px; margin-top: -2px; }  
  </style>  
  </apex:form>  
 </apex:page>  

When you preview this page you will be seeing red asterisk symbol in place of red vertical bar in visual force page for all inputFileds.

Output:


















When you click on save button without filling required fields marked as red asterisk it will throughs an error like Error: You must enter a value below each missing field.




Thanks for visiting..Enjoy......!

Trigger to update Rating field value based on Account Industry field

I'm trying to set Rating field value in Account object to 'Warm' whenever the Industry filed value on Account is Finance or Chemicals or HealthCare.

Possible Solutions:
  1.Using Workflows
  2.Using Triggers

In this post I'm trying to do this with the help of trigger only.Below is code snippet to implement this functionality with the help of trigger.

Source Code:
 trigger updateRatingTrigger on Account (before insert,before update)  
 {  
  if(Trigger.isBefore && (Trigger.isinsert || Trigger.isUpdate))  
  {  
    Set<String> setIndusry = new Set<String>{'Finance','Chemicals','HealthCare'};  
    for(Account acc: Trigger.new)  
    {  
    if(setIndusry.contains(acc.Industry) && acc.Rating!='Warm')  
     acc.Rating= 'Warm';  
    }  
  }  
 }  

Enjoy....!

Thursday, December 24, 2015

Apex Exception Email Option Under Email Adminstartion

Whenever an exception occurs in Apex ,code execution halts.Any DML operation performed will be rollbacked and those changes will not be committed.Exceptions gets logged in debug logs.

Unhandled Exceptions:

   Exceptions that are not handled in code or exceptions that the code doesn't catch are called as Unhanded exceptions.When these type of errors are occurred in code,salesforce sends an email to Last modified by user specified in class or trigger and an end users sees an error in the Salesforce user interface.This email report includes apex stack trace and the customer’s org and user ID. No other customer data is returned with the report.

Apex Exception Email Option :

  By using this option all unhanded exception emails are sent to Last modified by user and In addition to that you can sent same email report to user of the your organisation and to arbitrary email addresses(outside salesforce).

Apex Exception Email Apex Exception Email :

1. Goto Setup-->Email Administration-->Apex Exception Email.





























2. Select Add User option or add External user mail address separated by comma,semicolun,space,\t,\n or \r




3. Search for the user in your org and select then save.




Unhandled Exceptions in the User Interface:

If an end user runs into an exception that occurred in Apex code while using the standard user interface, an error message appears. The error message includes text similar to the notification shown below .




















Notes :

1.If duplicate exceptions occur in Apex code that runs synchronously, subsequent exception emails are suppressed and only the first email is sent. This email suppression prevents flooding of the developer’s inbox with emails about the same error. For asynchronous Apex, including batch Apex and methods annotated with @future, emails for duplicate exceptions aren’t suppressed.

2.You can also configure Apex exception emails using the Tooling API object ApexEmailNotification.


Wednesday, December 23, 2015

Salesforce Spring '16 Sandbox Preview Instructions

Important Notification from Salesforce 
The Salesforce Spring ‘16 release is quickly approaching and soon you'll be able to take advantage of exciting new features and functionality! If you are a Sandbox customer, you have the opportunity to get early access to Spring ‘16 in your Sandbox and test new customizations and features before your production organization is upgraded.
The Sandbox Preview window for Spring ‘16 is scheduled to begin January 8, 2016. If you would like your Sandbox organization to take part in the Spring ‘16 Preview, your Sandbox must be active on a preview instance by January 8, 2016 to take part in an overall instance upgrade.
For more Information Click here
Enjoy.........!

Tuesday, December 22, 2015

System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.

When I'm trying to execute a Test class I'm getting an System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.Looking at this error message I can say it is related to Flows or Process Builder but the thing is that how we need to identify in which flow it causing an error.In this post now I'm going to explain how to produce this issue and what is work around solution for this issue.

How to Produce the Issue

I have created a flow on Opportunity object with the help of Process builder .The main theme of the flow is that it has to execute an action after 6 days of  Opportunity Stage Name as Closed Won along with 2 more conditions.


Flow Criteria

1. Opportunity StageName equal "Closed Won" AND
2. Opportunity Amount is Greater than $25,000.00 AND
3. Opportunity related Account filed Sid_Desc__c(field in Account) is equals "Test"

Process Builder Flow is successfully created and activated.Please find the below image for clear picture





Now I'm going to write a sample test class to create a new opportunity

 @isTest  
  public class TestOppInsertFlow  
  {  
   static testMethod void insertOpp()  
   {  
   Opportunity op = new Opportunity();  
   op.Name = 'TestOpp';  
   op.StageName = 'Closed Won';  
   op.Closedate = System.today()+1;  
    insert op;  
   }  
  }  
When I am executing the above test class it will fail by displaying an error System.DmlException: Insert failed. First exception on row 0; first error: CANNOT_EXECUTE_FLOW_TRIGGER, The record couldn’t be saved because it failed to trigger a flow.

If you check in the debug logs you can clearly observe a flow error like The flow failed to access the value for myVariable_current.Account.SicDesc because it hasn't been set or assigned see below image.





Root Cause:


In flow we are referring the opportunity related Account filed value Sid_Desc__c but in our test class we are not passing any account value for the opportunity so it referring the Sid_Desc__c value in null account value.


Work Around Solution

1. By adding a null check for relation Ship fields in Process Builder(in our case AccountId)
 

 






































2. To pass the AccoutId value to the opportunity record in test class.See modified class below
 @isTest  
  public class TestOppInsertFlow  
  {  
   static testMethod void insertOpp()  
   {  
   Account acc = new Account();  
   acc.Name = 'tesst';  
   insert acc;  
   Opportunity op = new Opportunity();  
   op.Name = 'TestOpp';  
   op.StageName = 'Closed-Won';  
   op.Closedate = System.today()+1;  
   op.Accountid = acc.id;  
   insert op;  
   }  
  }  

3.If this issue is coming whenever your trying to perform deployment into Production and if you don't have time to fix this issue,best option is to deactivate it and perform deployment and activate it again

Note:
Whenever you encountered with this type of error you will be receiving an email from salesforce





















Enjoy....... Thanks for Visiting. Please follow us at FaceBook and twitter for more updates.

How to create a Tab Panel in Visaul Force Page

Whenever your planning to display any one or more objects data in visual force page .We can create a tabpanel and each tab represents one object.In this post I'm going to share simple example for tab panel and tab creation in visual force page.

Visual Force Page
 <apex:page controller="ListOfTabsCtrl">  
  <apex:pageBlock >  
   <apex:tabPanel width="1072px" >  
     <apex:tab label="Positions" labelWidth="358px" >  
      <apex:pageBlockTable value="{!listPos}" var="pos">  
        <apex:column >  
          <apex:outputLink value="/a07/e?CF00N1500000E1w1q={!pos.Name}&CF00N1500000E1w1q_lkid={!pos.id}" target="_blank">Apply </apex:outputLink>  
        </apex:column>  
        <apex:column value="{!pos.name}"/>  
        <apex:column value="{!pos.Status__c}"/>  
        <apex:column value="{!pos.Title__c}"/>  
        <apex:column value="{!pos.Closing_Date__c}"/>        
        <apex:column value="{!pos.Posting_URL__c}"/>  
        <apex:column value="{!pos.Category__c}"/>  
        <apex:column value="{!pos.Description__c}"/>  
       </apex:pageBlockTable>  
     </apex:tab>  
    <apex:tab label="Applicants" labelWidth="358px" >  
      <apex:pageBlockTable value="{!listApps}" var="apps">  
       <apex:column value="{!apps.name}"/>  
       <apex:column value="{!apps.First_Name__c}"/>  
       <apex:column value="{!apps.Last_Name__c}"/>  
       <apex:column value="{!apps.Mailing_Address1__c}"/>  
       <apex:column value="{!apps.Mailing_Address2__c}"/>  
       <apex:column value="{!apps.City__c}"/>  
       <apex:column value="{!apps.State__c}"/>  
       <apex:column value="{!apps.Zipcode__c}"/>  
       <apex:column value="{!apps.Email__c}"/>  
       <apex:column value="{!apps.Position_Id__c}"/>  
     </apex:pageBlockTable>  
    </apex:tab>  
    <apex:tab label="Categorys" labelWidth="358px">    
     <apex:pageBlockTable value="{!listCate}" var="cate">  
      <apex:column value="{!cate.Name}"/>  
       <apex:column value="{!cate.description__c }"/>  
     </apex:pageBlockTable>      
       </apex:tab>  
   </apex:tabPanel>  
 </apex:pageBlock>   
 </apex:page>  
Apex Class:
 public class ListOfTabsCtrl {  
  public List<Position__c> listPos{get;set;}  
  public List<Applicant__c> listApps{get;set;}  
  public List<Category__c> listCate{get;set;}  
  public ListOfTabsCtrl()  
  {  
  listPos = new List<Position__c>();  
  listApps = new List<Applicant__c>();  
  listCate = new List<Category__c>();  
  listPos = [SELECT Id, Name, Catg__c, Title__c, Description__c, Closing_Date__c, Posting_URL__c, Category__c, Status__c FROM Position__c where status__c ='Open'];  
  listApps = [SELECT Id, Name, First_Name__c, Last_Name__c, Mailing_Address1__c, Mailing_Address2__c, City__c, State__c, Zipcode__c, Email__c, Position_Id__c FROM Applicant__c];  
  listCate = [Select id,name,description__c from Category__c];  
  posTabSelected = true;  
  }  
 }  

Sample output look like as below image

Tuesday, December 15, 2015

Illegal assignment from LIST<Account> to LIST<Account> at line in Apex Class

Whenever you have return Query on any object if it is returning more than one record then we will be using the List datatype to store that result .Here is the some interesting issue that I faced when I am assigning my results of type List<Account> to List<Account>

Public class AccountController
{
 List<Account> listAcc{get;set;}
 public AccountController()
 {
    listAcc = new List<Account>();
 listAcc = [Select id,name FROM Account ];
 }
}

When I am execute this class I am getting an error at line Query Illegal assignment from LIST<Account> to LIST<Account> at line in Salesforce Class.
Here I'm getting list of accounts from query and I am assigning that to List<Account> listAcc only but why still I getting this error.I searched for it so many places finally I got the solution(Thanks for the Jitendra who provided me the solution).

WorkAround:
In my organization somewhere I have created a class named "Account". That is why the compiler is not able to understand that it is standard Object Account or the class created in my org.Now I renamed my class to some other name now it's working perfectly.

Monday, December 14, 2015

Scenario Based Salesforce Interview Questions

Check Out Topic Wise Top Interview Questions With Answers.New

1) You have a page with Standard Controller and one Extension class.In Extenstion class you have a method name called save().Now when your invoking save() method from page whether it will execute Standard Controller save() method or Extension class save() method?

Ans : The Save() method from the Extenstion class will be executed.

2) In a trigger you have addError() method and below that statement you have a System.debug() statement.If addError() method is executed in trigger in that case whether System.debug() statement will be executed or not?

Ans : Yes,Even after addError() method got executed the execution will not be stopped at that line and it will executes below the System.debug() statement also.

3) If in your organisation Person Account feature is enabled.Whenever your converting the Lead how you will decide which Account(Business or Person) to be created?

Ans : Based on the company field value on Lead we will decide whether to create Business Account or Person Account.If Company field value in Lead object is blank then we will create Person account on it's conversion and If Company Field value on Lead object is not blank we will create Business Account

4) How will say particular lead is a Business Lead or Person Lead?

Ans : Based on the company field value on Lead we will decide whether that Lead is Business Lead or Person Lead.If Company Field value is blank then it will be treated as Person Lead,If not it will be treated as Business Lead

5) Lets assume your having a object called Quotes and it is having 4 fields.Now I want to add one extra field to each and every record in Quote object without creating it in Object and I want to display list of Quote records on visual force page with 5 fields not with only 4 fields.

Ans : Whenever your working with these type of scenarios (i.e., Add extra field to each and every record in object actually not creating that field in object) we have to use Wrapper class concept which will add one or more fields for each and every record. 

6) When you will end up with MIXED_DML_OPERATION error in Salesforce?

Ans: With in a single transaction if you are trying to perform dml operations on setup objects and non-setup objects with same user(Logged in user) than it throws that error.To avoid that error we need to perform DML on Set up objects with logged in user and on non setup objects with some other user using System.runAs() and vice versa

7) What are the limitations/considerations for Time-Dependent Workflow?
  • You can not write time-dependent action on workflow rule Evaluation Criteria of type Every time the record is created or updated.
  • Maximum you can write 10 time dependent triggers per one rule
  • Maximum of 40 actions only allowed per time trigger.
  • Workflow default user must be set up before creating time-based rules
  • Precision limited to hours or days
  • Cannot convert leads with time-dependent actions in the Workflow Queue.
  • Time triggers cannot be added to or removed from activated workflow rules

8) While setting OWD (Organization wide sharing), can we change/modify the setting of child record in case of Master-Detail relationship?

Ans: No, child record is controlled by parent settings.

9) In case of Master-Detail relationship, on Update of child record can we update the field of Parent record using workflow rule?

Ans: Yes, the Master fields are also available for evaluation criteria.So, we can acheive this with workflow.For more information please visit this post

10) Who can access “drag and drop dashboard”?Which type of report can be used for dashboard components?

Ans : User who have permissions in managed dashboard can access drag and drop dashboard.Summary reports and Matrix reports are used for dashboard components.

Thanks for visiting..Enjoy.....



Friday, December 11, 2015

How to know whether JQuery library loaded properly or not in Visual Force Page

Whenever we are working with any jQuery related stuff in visual force page first we have to load the JQuery library in visual force page.Now in this post I am going to explain how to load jQuery in visual force and how to test whether jQuery files are loaded properly or not.

Loading the jQuery in VisaulForce Page

 

Using Static Resources 

1. Download the latest jQuery package from here 
2. Place the downloaded package in Static resources of Salesofrce
3. Include that Static resource file  in the visual force page

 <apex:includeScript value="{!URLFOR($Resource.MyStaticResourceName}" />  
 <apex:includeScript value="{!URLFOR($Resource.MyStaticResourceName, '/js/jquery-ui-1.8.6.custom.min.js')}" />  
 <apex:stylesheet value="{!URLFOR($Resource.MyStaticResourceName, '/css/ui-lightness/jquery-ui-1.8.6.custom.css')}" />  

Directly including the Jquery CDN url in visual force page

 <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"/>  
 <apex:stylesheet value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.css"/>  

Test whether jQuery loaded properly or not 

 1.Cretae a below sample page and execute
 <apex:page standardController="Account">  
 <apex:includeScript value="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"/>  
 <apex:stylesheet value="https://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/ui-lightness/jquery-ui.css"/>  
  <script type="text/javascript">  
    var j$ = jQuery.noConflict();  //Which tells whether any conflict or not
    if(j$)  
    {  
    alert('No conflict,jQuery loaded successfully');  
    }  
    else  
    {  
    alert('Error while loading the jQuery');  
    }  
  </script>  
 </apex:page>  

2.  The noConflict() (highlighted in yellow)method in jQuery will tells that whether it loaded properly or any conflicts got occurred while loading .If successfully loaded it reruns true else it returns false.

3. If succesfully loaded will alert the user with
   No conflict,jQuery loaded successfully
    else
   Error while loading the jQuery


Thanks for visiting..Enjoy

Thursday, December 10, 2015

System.LimitException: DML currently not allowed

Whenever we trying to perform any DML operations at the time of initial page load we will be ending up with an error called System.LimitException: DML currently not allowed. In this post I am going to show how to produce the issue with simple example and workaround for the same issue.

1.Create simple page and class as shown below

VF Page Name : DeleteAllConts
 <apex:page controller="DeleteAllContCtrl">  
 </apex:page>  

Controller
1:  public class DeleteAllContCtrl  
2:  {  
3:   public DeleteAllContCtrl()  
4:   {  
5:    Id AccId = Apexpages.CurrentPage().getParameters().get('id');    
6:    Delete ([SELECT id FROM Contact WHERE AccountID=:AccId]);  
7:   }  
8:  }  

Now create a simple page with hyperlink and run it by passing any AccountID
1:  <apex:page standardController="Account">  
2:        <apex:outputLink value="/apex/DeleteAllConts?id={!Account.id}"> Delete All Contacts</apex:outputLink>   
3:  </apex:page>  

When user clicks on link it will be calling the DeleteAllConts page by passing the current AccountID as parameter.Once the execution starts at the controller it will be throwing an error System.LimitException: DML currently not allowed at delete statement(line number 6) in DeleteAllContCtrl class.

Reason for the Error:
1.When you are trying invoke any controller from visual force page to perform any dml operations (insert/delete/update/upsert) inside the constructor or any method called from constructor it will not allowed.
2.Within a single transaction - Web Service callouts just after the DML operation.(Thanks for Girish for providing this point)

Workaround for solutions 

1. Move the dml statements out of the constructor
2.Create a method place that dml operations inside that method and invoke that method directly from page using the action attribute in <apex:page> tag

Modified DeleteAllConts Page and Controller

 <apex:page controller="DeleteAllContCtrl" action="{!delContacts}">  
 </apex:page>  

1:  public class DeleteAllContCtrl  
2:  {  
3:   public DeleteAllContCtrl()  
4:   {  
5:    System.debug('Eneterd Inside Contsructor');  
6:   }  
7:   public void delContacts()  
8:   {  
9:    Id AccId = Apexpages.CurrentPage().getParameters().get('id');    
10:    Delete ([SELECT id FROM Contact WHERE AccountID=:AccId]);  
11:   }  
12:  }  

Thanks for visiting....Enjoy.....

Thursday, December 3, 2015

How to get salesforce base URL in visual force page at runtime

When we are writing any code related to Salesforce Instance URL it shouldn't be hard coded.The reason behind it when you deeply the the same code to other environments like sandboxes or production the base URL might be changed based on instances.At that point of time your code might breaks and it will stop working.

So whenever your dealing with any URL related stuff it's better to get the instance URL(BaseURL,any other parameters) at run time based on the instance.There are already so many ways that you can get the baseURL in apex but if you want to get it in vf page one way is as below

Getting salesforce instance URL in VF page

<script>
   var totalPageURL = window.location.toString();
   var protocalType= totalPageURL.split("//")[0];
   var tempbaseURL = totalPageURL.split("//")[1].split("/");
   var finalBaseURL = protocalType+'//'+tempbaseURL[0];
   alert(finalBaseURL );
</script>

Example:

Input
Lets take if your page url is like https://cs26.salesforce.com/800/o

Output
Then this will give output as https://cs26.salesforce.com (which is baseURL)

To test this snippet on any web page 

1. Just open any web page 
2. Press F12 (for chrome) or Right click open inspect element
3. Click on console 
4. Paste the code by removing <script> tag and press enter

Then you will popup with alert message which displays your BaseURL.

For more info please refer highlighted areas in below image 


























Thanks for visiting..Enjoy.....