A blog containing Salesforce coding examples in detail.It's a place where you can find solutions to the problems that you may face in your daily salesforce coding. Apex classes,visual force page,we services,Integration,plugins,extensions,Lightning web components,Aura components,Email Messages,Sales cloud,service Cloud,Marketing Cloud.Lightning Web components,salesforce.com, Salesforce Tips and Tricks,short cuts,ApexMocks,Stubs, visibility,Salesforce Shorts
Thursday, December 31, 2015
Tuesday, December 29, 2015
Select All Checkbox in Visualforce Page
Apex Code :
public class SelectAll {
public List <Account> accountList {get;set;}
public SelectAll () {
accountList = [select id,name,phone,AccountSource,type from Account limit 5];
}
}
Visualforce Page :
<apex:page controller="SelectAll">
<script>
function selectAllCheckboxes(obj,receivedInputID){
var inputCheckBox = document.getElementsByTagName("input");
for(var i=0; i<inputCheckBox.length; i++){
if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1) {
inputCheckBox[i].checked = obj.checked;
}
}
}
</script>
<apex:form>
<apex:pageBlock >
<apex:pageBlockTable value="{!accountList}" var="acc" id="AccountTable">
<apex:column headerValue="Action" >
<apex:facet name="header">
<apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')">
<apex:actionSupport event="onchange" reRender="AccountTable"/>
</apex:inputCheckbox>
</apex:facet>
<apex:inputCheckbox id="inputId" value="{!acc.id}" >
<apex:actionSupport event="onchange" />
</apex:inputCheckbox>
</apex:column>
<apex:column headerValue="Account Name" >
{!acc.name}
</apex:column>
<apex:column headerValue="Phone" >
{!acc.phone}
</apex:column>
<apex:column headerValue="Type" >
{!acc.type}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
public class SelectAll {
public List <Account> accountList {get;set;}
public SelectAll () {
accountList = [select id,name,phone,AccountSource,type from Account limit 5];
}
}
Visualforce Page :
<apex:page controller="SelectAll">
<script>
function selectAllCheckboxes(obj,receivedInputID){
var inputCheckBox = document.getElementsByTagName("input");
for(var i=0; i<inputCheckBox.length; i++){
if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1) {
inputCheckBox[i].checked = obj.checked;
}
}
}
</script>
<apex:form>
<apex:pageBlock >
<apex:pageBlockTable value="{!accountList}" var="acc" id="AccountTable">
<apex:column headerValue="Action" >
<apex:facet name="header">
<apex:inputCheckbox onclick="selectAllCheckboxes(this,'inputId')">
<apex:actionSupport event="onchange" reRender="AccountTable"/>
</apex:inputCheckbox>
</apex:facet>
<apex:inputCheckbox id="inputId" value="{!acc.id}" >
<apex:actionSupport event="onchange" />
</apex:inputCheckbox>
</apex:column>
<apex:column headerValue="Account Name" >
{!acc.name}
</apex:column>
<apex:column headerValue="Phone" >
{!acc.phone}
</apex:column>
<apex:column headerValue="Type" >
{!acc.type}
</apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
Saturday, December 26, 2015
Update all contacts phone number with associated account's phone number when associated account is updated
Assume Phone field of Account and Phone field of contact are used here in example.
Sample Code:
trigger updatePhone on Account (after update) {
Set <Id> accountIdSet = new Set <Id>();
Map <Id,String> accountMap = new Map <Id,string> ();
for(Account acc:trigger.new) {
if(Trigger.oldMap.get(acc.Id).phone != acc.phone) {
accountIdSet.add(acc.id);
}
if(acc.phone != null) {
accountMap.put(acc.id,acc.phone);
}
}
List <contact> contactList = new List <Contact>();
for(Contact con:[select id,accountId,Phone from contact where accountId in:accountIdSet]) {
if(accountMap != null && accountMap.containsKey(con.accountId)) {
con.phone = accountMap.get(con.accountId);
contactList.add(con);
}
}
if(contactList.size() >0) {
update contactList;
}
}
Output:
Sample Code:
trigger updatePhone on Account (after update) {
Set <Id> accountIdSet = new Set <Id>();
Map <Id,String> accountMap = new Map <Id,string> ();
for(Account acc:trigger.new) {
if(Trigger.oldMap.get(acc.Id).phone != acc.phone) {
accountIdSet.add(acc.id);
}
if(acc.phone != null) {
accountMap.put(acc.id,acc.phone);
}
}
List <contact> contactList = new List <Contact>();
for(Contact con:[select id,accountId,Phone from contact where accountId in:accountIdSet]) {
if(accountMap != null && accountMap.containsKey(con.accountId)) {
con.phone = accountMap.get(con.accountId);
contactList.add(con);
}
}
if(contactList.size() >0) {
update contactList;
}
}
Output:
Friday, December 25, 2015
Difference between with sharing and without sharing keywords
With Sharing:The "With Sharing" keyword allows us to specify that the sharing rules for the current user are enforced(taken into consideration).
Without Sharing(system context) :In general Apex code runs in system context.In system context,Apex code has access to all objects and fields-object permissions,field-level security.Sharing rules are not applied for the current user.
Note:Apex code which is executed through executeAnonymous call has full permissions for the current user.
Important Points:
1) The sharing setting of the class where the method is defined is applied,not of the class where the method is called.
Example:If a method is defined in a class declared with with sharing keyword is called by a class declared with withoutsharing keyword,then that method will execute with sharing rules enforced.
2) If a class is not declared as either with or without sharing,the current sharing rules remain in effect.
3) Both inner classes and outer classes can be declared as with sharing.The sharing setting applies to all code contained in the class,including initialization code,constructors and methods
4) Inner classes do not inherit the sharing setting from their container class.
Without Sharing(system context) :In general Apex code runs in system context.In system context,Apex code has access to all objects and fields-object permissions,field-level security.Sharing rules are not applied for the current user.
Note:Apex code which is executed through executeAnonymous call has full permissions for the current user.
Important Points:
1) The sharing setting of the class where the method is defined is applied,not of the class where the method is called.
Example:If a method is defined in a class declared with with sharing keyword is called by a class declared with withoutsharing keyword,then that method will execute with sharing rules enforced.
2) If a class is not declared as either with or without sharing,the current sharing rules remain in effect.
3) Both inner classes and outer classes can be declared as with sharing.The sharing setting applies to all code contained in the class,including initialization code,constructors and methods
4) Inner classes do not inherit the sharing setting from their container class.
Tuesday, December 22, 2015
HelpText in Visualforce Page
HelpText in Visualforce Page
Example Code:
<apex:page standardController="Account">
<style type="text/css">
.imgclass:hover{
background-image: url(/img/help/helpOrbs.gif);
background-repeat: no-repeat;
width: 16px;
height: 15px;
background-position: right;
}
.imgclass{
background-image: url(/img/help/helpOrbs.gif);
background-repeat: no-repeat;
width: 16px;
height: 15px;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Enter Information">
<apex:pageblockSectionItem >
<apex:outputPanel >
<apex:outputlabel value="Enter Account Name"/>
<img src="/s.gif" Class="imgclass" title="Please Enter Account Name" />
</apex:outputPanel>
<apex:inputField value="{!Account.Name}"/>
</apex:pageblockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
Example Code:
<apex:page standardController="Account">
<style type="text/css">
.imgclass:hover{
background-image: url(/img/help/helpOrbs.gif);
background-repeat: no-repeat;
width: 16px;
height: 15px;
background-position: right;
}
.imgclass{
background-image: url(/img/help/helpOrbs.gif);
background-repeat: no-repeat;
width: 16px;
height: 15px;
}
</style>
<apex:form >
<apex:pageBlock >
<apex:pageBlockSection title="Enter Information">
<apex:pageblockSectionItem >
<apex:outputPanel >
<apex:outputlabel value="Enter Account Name"/>
<img src="/s.gif" Class="imgclass" title="Please Enter Account Name" />
</apex:outputPanel>
<apex:inputField value="{!Account.Name}"/>
</apex:pageblockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
Sunday, December 13, 2015
How to check whether the value is numeric or Non-numeric
Example 1:
String value = 'abc';
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',value);
if(isNonNumericValue == true) {
system.debug('Non Numeric');
} else {
system.debug('Numeric');
}
Output:
Example 2:
String value = '123';
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',value);
if(isNonNumericValue == true) {
system.debug('Non Numeric');
} else {
system.debug('Numeric');
}
Output:
String value = 'abc';
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',value);
if(isNonNumericValue == true) {
system.debug('Non Numeric');
} else {
system.debug('Numeric');
}
Output:
Example 2:
String value = '123';
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',value);
if(isNonNumericValue == true) {
system.debug('Non Numeric');
} else {
system.debug('Numeric');
}
Output:
Web to Lead
Web to Lead: When you setup Web to Lead,You can automatically generate upto 500 leads per day with the prospecting data from your company's website visitors.
Enable Web to Lead: Go to setup --> customize --> Leads --> web-to-lead --> Enable "web to lead" checkbox.
How to send default Email Response: In order to send default email response,select the "Default Response Template" in web-to-lead settings.
Process : First we need to generate "web to lead form" as required and then we need to place that generated form related html code in our websites.
step 1: Go to setup --> customize --> Leads --> web-to-lead --> click "Create Web-to-Lead Form" button.
step 2: Select the required fields which need to be displayed in form .
step 3: After users submit the web-to-lead form,they can be redirected to our required url or website or "thank you" page by providing the URL in "Return URL
step 4:Click "Generate" Button.
step 5:Click on the text area box and press ctrl+A and then press ctrl+c to copy.
step 6: Paste this html code in required websites.
Here I created webtolead.html page.
Code : webtolead.html
<!-- ---------------------------------------------------------------------- -->
<!-- NOTE: Please add the following <META> element to your page <HEAD>. -->
<!-- If necessary, please modify the charset parameter to specify the -->
<!-- character set of your HTML page. -->
<!-- ---------------------------------------------------------------------- -->
<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8">
<!-- ---------------------------------------------------------------------- -->
<!-- NOTE: Please add the following <FORM> element to your page. -->
<!-- ---------------------------------------------------------------------- -->
<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
<input type=hidden name="oid" value="00D28000000c5N4">
<input type=hidden name="retURL" value="https://salesforceglobe4u.blogspot.com/">
<!-- ---------------------------------------------------------------------- -->
<!-- NOTE: These fields are optional debugging elements. Please uncomment -->
<!-- these lines if you wish to test in debug mode. -->
<!-- <input type="hidden" name="debug" value=1> -->
<!-- <input type="hidden" name="debugEmail" value="suneel522.k@gmail.com"> -->
<!-- ---------------------------------------------------------------------- -->
<label for="first_name">First Name</label><input id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br>
<label for="last_name">Last Name</label><input id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br>
<label for="email">Email</label><input id="email" maxlength="80" name="email" size="20" type="text" /><br>
<label for="company">Company</label><input id="company" maxlength="40" name="company" size="20" type="text" /><br>
<label for="city">City</label><input id="city" maxlength="40" name="city" size="20" type="text" /><br>
<label for="state">State/Province</label><input id="state" maxlength="20" name="state" size="20" type="text" /><br>
<input type="submit" name="submit">
</form>
Output:Open that page in any browser.
Fill all the details
Click "Submit" button
You can also observe that auto response email is sent to the email specified in form.
Enable Web to Lead: Go to setup --> customize --> Leads --> web-to-lead --> Enable "web to lead" checkbox.
How to send default Email Response: In order to send default email response,select the "Default Response Template" in web-to-lead settings.
Process : First we need to generate "web to lead form" as required and then we need to place that generated form related html code in our websites.
step 1: Go to setup --> customize --> Leads --> web-to-lead --> click "Create Web-to-Lead Form" button.
step 2: Select the required fields which need to be displayed in form .
step 4:Click "Generate" Button.
step 5:Click on the text area box and press ctrl+A and then press ctrl+c to copy.
step 6: Paste this html code in required websites.
Here I created webtolead.html page.
Code : webtolead.html
<!-- ---------------------------------------------------------------------- -->
<!-- NOTE: Please add the following <META> element to your page <HEAD>. -->
<!-- If necessary, please modify the charset parameter to specify the -->
<!-- character set of your HTML page. -->
<!-- ---------------------------------------------------------------------- -->
<META HTTP-EQUIV="Content-type" CONTENT="text/html; charset=UTF-8">
<!-- ---------------------------------------------------------------------- -->
<!-- NOTE: Please add the following <FORM> element to your page. -->
<!-- ---------------------------------------------------------------------- -->
<form action="https://www.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8" method="POST">
<input type=hidden name="oid" value="00D28000000c5N4">
<input type=hidden name="retURL" value="https://salesforceglobe4u.blogspot.com/">
<!-- ---------------------------------------------------------------------- -->
<!-- NOTE: These fields are optional debugging elements. Please uncomment -->
<!-- these lines if you wish to test in debug mode. -->
<!-- <input type="hidden" name="debug" value=1> -->
<!-- <input type="hidden" name="debugEmail" value="suneel522.k@gmail.com"> -->
<!-- ---------------------------------------------------------------------- -->
<label for="first_name">First Name</label><input id="first_name" maxlength="40" name="first_name" size="20" type="text" /><br>
<label for="last_name">Last Name</label><input id="last_name" maxlength="80" name="last_name" size="20" type="text" /><br>
<label for="email">Email</label><input id="email" maxlength="80" name="email" size="20" type="text" /><br>
<label for="company">Company</label><input id="company" maxlength="40" name="company" size="20" type="text" /><br>
<label for="city">City</label><input id="city" maxlength="40" name="city" size="20" type="text" /><br>
<label for="state">State/Province</label><input id="state" maxlength="20" name="state" size="20" type="text" /><br>
<input type="submit" name="submit">
</form>
Output:Open that page in any browser.
Fill all the details
You can also observe that auto response email is sent to the email specified in form.
Saturday, December 12, 2015
Tree Structure in visualforce page(upto 4 levels)
Apex class:
public with sharing class TreeStructure {
public List <Account> accountList{get; set;}
public List <contact> contactList{get; set;}
public List <case> caseList{get; set;}
public List <CaseComment> caseCommentList{get; set;}
List <Id> accountIds =new List<Id>();
List <Id> contactIds =new List<Id>();
List <Id> caseIds =new List<Id>();
public TreeStructure() {
accountList = [Select id, name,parentid from account limit 200];
for(account a:accountList ) {
accountIds.add(a.id);
}
contactList = [Select id, name,accountid from contact where accountid in:accountIds ];
for(contact a:contactList ) {
contactIds.add(a.id);
}
caseList = [Select id,casenumber,contactid from case where contactid in:contactIds ];
for(case a:caseList ) {
caseIds.add(a.id);
}
caseCommentList = [Select id,CommentBody,parentid from CaseComment where parentid in:caseIds ];
}
}
Static Resource: create a static resource with name "Jtreeview" and upload the file downloaded from this link JTree Static Resource.
Visualforce Page :
<apex:page sidebar="false" controller="TreeStructure" showheader="false">
<!-- Include the Jquery Script files -->
<link rel="stylesheet" href="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.treeview.css')}"/>
<script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.js')}" type="text/javascript"></script>
<script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.cookie.js')}" type="text/javascript"></script>
<script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.treeview.js')}" type="text/javascript"></script>
<!-- End of Javascript files -->
<script type="text/javascript">
$(function() {
$("#tree").treeview({
collapsed: false,
animated: "medium",
control:"#sidetreecontrol",
persist: "location"
});
})
</script>
<br/> <br/> <br/>
<!-- Tree -->
<div class="treeheader" style="height:0px;"> </div>
<div id="sidetreecontrol"><a href="?#"><font style="color:blue;">Collapse All</font></a> | <a href="?#"><font style="color:blue;">Expand All</font></a></div>
<ul id="tree">
<apex:repeat value="{!accountList}" var="acc">
<li class="closed"><span class="folder">{!acc.name}</span>
<ul>
<apex:repeat value="{!contactList}" var="c">
<apex:outputtext rendered="{!c.accountid==acc.id}"><li><span class="file"><a href="/{!c.id}" target="_blank">{!c.name}</a></span>
<ul>
<apex:repeat value="{!caseList}" var="c1">
<apex:outputtext rendered="{!c1.contactid==c.id}"><li><span class="file"><a href="/{!c1.id}" target="_blank">{!c1.casenumber}</a></span>
<ul>
<apex:repeat value="{!caseCommentList}" var="c2">
<apex:outputtext rendered="{!c2.parentid==c1.id}"> <li><span class="file"><a href="/{!c.id}" target="_blank">{!c2.CommentBody}</a></span>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
<apex:repeat value="{!accountList}" var="acc1" first="1">
<apex:outputtext rendered="{!acc1.parentid==acc.id}"><li class="closed"><span class="folder">{!acc1.name}</span>
<ul>
<apex:repeat value="{!contactList}" var="c">
<apex:outputtext rendered="{!c.accountid==acc1.id}"><li><span class="file"><a href="/{!c.id}" target="_blank">{!c.name}</a></span>
<ul>
<apex:repeat value="{!caseList}" var="c1">
<apex:outputtext rendered="{!c1.contactid==c.id}"><li><span class="file"><a href="/{!c1.id}" target="_blank">{!c1.casenumber}</a></span>
<ul>
<apex:repeat value="{!caseCommentList}" var="c2">
<apex:outputtext rendered="{!c2.parentid==c1.id}"> <li><span class="file"><a href="/{!c.id}" target="_blank">{!c2.CommentBody}</a></span>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li>
</apex:outputtext></apex:repeat>
</ul>
</li>
</apex:repeat>
</ul>
<!-- End of Tree -->
</apex:page>
Output:
public with sharing class TreeStructure {
public List <Account> accountList{get; set;}
public List <contact> contactList{get; set;}
public List <case> caseList{get; set;}
public List <CaseComment> caseCommentList{get; set;}
List <Id> accountIds =new List<Id>();
List <Id> contactIds =new List<Id>();
List <Id> caseIds =new List<Id>();
public TreeStructure() {
accountList = [Select id, name,parentid from account limit 200];
for(account a:accountList ) {
accountIds.add(a.id);
}
contactList = [Select id, name,accountid from contact where accountid in:accountIds ];
for(contact a:contactList ) {
contactIds.add(a.id);
}
caseList = [Select id,casenumber,contactid from case where contactid in:contactIds ];
for(case a:caseList ) {
caseIds.add(a.id);
}
caseCommentList = [Select id,CommentBody,parentid from CaseComment where parentid in:caseIds ];
}
}
Static Resource: create a static resource with name "Jtreeview" and upload the file downloaded from this link JTree Static Resource.
Visualforce Page :
<apex:page sidebar="false" controller="TreeStructure" showheader="false">
<!-- Include the Jquery Script files -->
<link rel="stylesheet" href="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.treeview.css')}"/>
<script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.js')}" type="text/javascript"></script>
<script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.cookie.js')}" type="text/javascript"></script>
<script src="{!URLFOR($Resource.Jtreeview,'Jquerytreeview/jquery.treeview.js')}" type="text/javascript"></script>
<!-- End of Javascript files -->
<script type="text/javascript">
$(function() {
$("#tree").treeview({
collapsed: false,
animated: "medium",
control:"#sidetreecontrol",
persist: "location"
});
})
</script>
<br/> <br/> <br/>
<!-- Tree -->
<div class="treeheader" style="height:0px;"> </div>
<div id="sidetreecontrol"><a href="?#"><font style="color:blue;">Collapse All</font></a> | <a href="?#"><font style="color:blue;">Expand All</font></a></div>
<ul id="tree">
<apex:repeat value="{!accountList}" var="acc">
<li class="closed"><span class="folder">{!acc.name}</span>
<ul>
<apex:repeat value="{!contactList}" var="c">
<apex:outputtext rendered="{!c.accountid==acc.id}"><li><span class="file"><a href="/{!c.id}" target="_blank">{!c.name}</a></span>
<ul>
<apex:repeat value="{!caseList}" var="c1">
<apex:outputtext rendered="{!c1.contactid==c.id}"><li><span class="file"><a href="/{!c1.id}" target="_blank">{!c1.casenumber}</a></span>
<ul>
<apex:repeat value="{!caseCommentList}" var="c2">
<apex:outputtext rendered="{!c2.parentid==c1.id}"> <li><span class="file"><a href="/{!c.id}" target="_blank">{!c2.CommentBody}</a></span>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
<apex:repeat value="{!accountList}" var="acc1" first="1">
<apex:outputtext rendered="{!acc1.parentid==acc.id}"><li class="closed"><span class="folder">{!acc1.name}</span>
<ul>
<apex:repeat value="{!contactList}" var="c">
<apex:outputtext rendered="{!c.accountid==acc1.id}"><li><span class="file"><a href="/{!c.id}" target="_blank">{!c.name}</a></span>
<ul>
<apex:repeat value="{!caseList}" var="c1">
<apex:outputtext rendered="{!c1.contactid==c.id}"><li><span class="file"><a href="/{!c1.id}" target="_blank">{!c1.casenumber}</a></span>
<ul>
<apex:repeat value="{!caseCommentList}" var="c2">
<apex:outputtext rendered="{!c2.parentid==c1.id}"> <li><span class="file"><a href="/{!c.id}" target="_blank">{!c2.CommentBody}</a></span>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li></apex:outputtext>
</apex:repeat>
</ul>
</li>
</apex:outputtext></apex:repeat>
</ul>
</li>
</apex:repeat>
</ul>
<!-- End of Tree -->
</apex:page>
Output:
Friday, December 11, 2015
Invalid integer:abc.An unexpected error has occured.Your development organization has been notified.
Example:
Apex Class:
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null && accountList[0].AccountNumber != null) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
Visualforce Page:
<apex:page controller="ArgumentNotNull">
The integer value :{!intValue }
</apex:page>
Problem: In the example above, the "accountList[0].AccountNumber" returns string value and we are trying to convert it into Integer.
Solution : First check whether the value is string or integer,then we need to typecast if necessary.
Modify the above class like this.
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null && accountList[0].AccountNumber != null) {
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',accountList[0].AccountNumber);
if(isNonNumericValue == false) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
}
Apex Class:
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null && accountList[0].AccountNumber != null) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
Visualforce Page:
<apex:page controller="ArgumentNotNull">
The integer value :{!intValue }
</apex:page>
Problem: In the example above, the "accountList[0].AccountNumber" returns string value and we are trying to convert it into Integer.
Solution : First check whether the value is string or integer,then we need to typecast if necessary.
Modify the above class like this.
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null && accountList[0].AccountNumber != null) {
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',accountList[0].AccountNumber);
if(isNonNumericValue == false) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
}
Thursday, December 10, 2015
Argument cannot be null.An unexpected error has occured.Your development organization has been notified.
Example :
Apex Class :
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
Visualforce Page :
<apex:page controller="ArgumentNotNull">
The integer value :{!intValue }
</apex:page>
Assume you didnot enter any value in accountnumber field of Account with record id "00128000003yhTi".
In the line "intValue = Integer.valueof(accountList[0].AccountNumber);" since accountList[0].Accountnumber value is null,We are getting the above error.
Solution: We need to add null check before going to the above line.
Modify the above apex class as:
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null && accountList[0].AccountNumber != null) {
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',accountList[0].AccountNumber);
if(isNonNumericValue == false) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
}
Apex Class :
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
Visualforce Page :
<apex:page controller="ArgumentNotNull">
The integer value :{!intValue }
</apex:page>
Assume you didnot enter any value in accountnumber field of Account with record id "00128000003yhTi".
In the line "intValue = Integer.valueof(accountList[0].AccountNumber);" since accountList[0].Accountnumber value is null,We are getting the above error.
Solution: We need to add null check before going to the above line.
Modify the above apex class as:
public class ArgumentNotNull {
public Integer intValue {get;set;}
public ArgumentNotNull () {
List <Account> accountList = [select id,name,AccountNumber from Account where id=:'00128000003yhTi'];
if(accountList != null && accountList[0].AccountNumber != null) {
boolean isNonNumericValue = pattern.matches('[a-zA-Z]+',accountList[0].AccountNumber);
if(isNonNumericValue == false) {
intValue = Integer.valueof(accountList[0].AccountNumber);
}
}
}
}
How to create splash page in salesforce
Splash Page Custom Link : It is the page which will appear when we click the tab for the first time and then creation of tab will continue as it is.
Step 1: Create custom link.Go to Setup --> Home --> custom Links --> click "New" Button -->Fill details --> save.
Step 2: Now create new Tab or modify existing tab.Go to setup --> Create --> Tabs.
Click "New" button of any section
In the above image, after selecting object and tab style, we have "Splash Page custom Link" where we select the custom link which we created earlier.
click "Next" --> Next --> Save.
Step 3: Now click on the tab created.
Output:
Step 1: Create custom link.Go to Setup --> Home --> custom Links --> click "New" Button -->Fill details --> save.
Step 2: Now create new Tab or modify existing tab.Go to setup --> Create --> Tabs.
Click "New" button of any section
In the above image, after selecting object and tab style, we have "Splash Page custom Link" where we select the custom link which we created earlier.
click "Next" --> Next --> Save.
Step 3: Now click on the tab created.
Output:
Wednesday, December 9, 2015
Hide and show PageBlockTable
Apex Code :
public class HideAndShowPageBlockTable {
public List <Account> accountList {get;set;}
public List<Account> fetchAccounts() {
accountList = [Select Id,(Select id,name From contacts), Name, BillingCountry from Account];
return accountList ;
}
}
Create a static resource with name "Plus_Image" for Plus image.
Create a static resource with name "Minus_Image" for Minusimage.
You can download that images from the url : static resource.
Visualforce Page :
<apex:page tabstyle="Account" controller="HideAndShowPageBlockTable" showheader="false">
<script>
function switchMenu(obj,obj1,obj2) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
var e2 = document.getElementById(obj1);
if ( e2.style.display != 'none' ) {
e2.style.display = 'none';
}
else {
e2.style.display = '';
}
var e3 = document.getElementById(obj2);
if ( e2.style.display != 'none' ) {
e3.style.display = 'none';
}
else {
e3.style.display = '';
}
}
</script>
<apex:pageblock >
<apex:pageblocktable value="{!accountList}" var="acc">
<apex:column headervalue="Account Details">
<apex:outputpanel id="plusimage">
<apex:image url="{!$Resource.Plus_Image}" onclick="switchMenu('{!$Component.inlinetablesec}','{!$Component.minusimage}','{!$Component.plusimage}')" title="Expand - Team Member's"> </apex:image>
</apex:outputpanel>
<apex:outputpanel id="minusimage" style="display:none;">
<apex:image url="{!$Resource.Minus_Image}" onclick="switchMenu('{!$Component.inlinetablesec}','{!$Component.plusimage}','{!$Component.minusimage}')" title="Collapse - Team Member's"></apex:image>
</apex:outputpanel>
<apex:outputtext value="{!acc.Name}"/>
</apex:column>
<apex:column breakBefore="true">
<apex:outputpanel id="inlinetablesec" style="display:none;">
<apex:pageblocktable value="{!acc.contacts}" var="con" >
<apex:column headerValue="Contact Name">
<apex:outputfield value="{!con.Name}"/>
</apex:column>
<apex:column headerValue="Contact ID">
<apex:outputfield value="{!con.id}"/>
</apex:column>
</apex:pageblocktable>
</apex:outputpanel>
</apex:column>
</apex:pageblocktable>
</apex:pageblock>
</apex:page>
Output :
public class HideAndShowPageBlockTable {
public List <Account> accountList {get;set;}
public List<Account> fetchAccounts() {
accountList = [Select Id,(Select id,name From contacts), Name, BillingCountry from Account];
return accountList ;
}
}
Create a static resource with name "Plus_Image" for Plus image.
Create a static resource with name "Minus_Image" for Minusimage.
You can download that images from the url : static resource.
Visualforce Page :
<apex:page tabstyle="Account" controller="HideAndShowPageBlockTable" showheader="false">
<script>
function switchMenu(obj,obj1,obj2) {
var el = document.getElementById(obj);
if ( el.style.display != 'none' ) {
el.style.display = 'none';
}
else {
el.style.display = '';
}
var e2 = document.getElementById(obj1);
if ( e2.style.display != 'none' ) {
e2.style.display = 'none';
}
else {
e2.style.display = '';
}
var e3 = document.getElementById(obj2);
if ( e2.style.display != 'none' ) {
e3.style.display = 'none';
}
else {
e3.style.display = '';
}
}
</script>
<apex:pageblock >
<apex:pageblocktable value="{!accountList}" var="acc">
<apex:column headervalue="Account Details">
<apex:outputpanel id="plusimage">
<apex:image url="{!$Resource.Plus_Image}" onclick="switchMenu('{!$Component.inlinetablesec}','{!$Component.minusimage}','{!$Component.plusimage}')" title="Expand - Team Member's"> </apex:image>
</apex:outputpanel>
<apex:outputpanel id="minusimage" style="display:none;">
<apex:image url="{!$Resource.Minus_Image}" onclick="switchMenu('{!$Component.inlinetablesec}','{!$Component.plusimage}','{!$Component.minusimage}')" title="Collapse - Team Member's"></apex:image>
</apex:outputpanel>
<apex:outputtext value="{!acc.Name}"/>
</apex:column>
<apex:column breakBefore="true">
<apex:outputpanel id="inlinetablesec" style="display:none;">
<apex:pageblocktable value="{!acc.contacts}" var="con" >
<apex:column headerValue="Contact Name">
<apex:outputfield value="{!con.Name}"/>
</apex:column>
<apex:column headerValue="Contact ID">
<apex:outputfield value="{!con.id}"/>
</apex:column>
</apex:pageblocktable>
</apex:outputpanel>
</apex:column>
</apex:pageblocktable>
</apex:pageblock>
</apex:page>
Output :
Tuesday, December 8, 2015
How to display only 2 decimal values of a number in visualforce page (Restricting number of decimal values)
Apex Class:
Public class RestrictDecimalPlaces {
public decimal weight {get;set;}
public RestrictDecimalPlaces () {
weight = 50.6789;
}
}
Visualforce Page:
<apex:page controller="RestrictDecimalPlaces">
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.0}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 1 decimals)<br/><br/>
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.00}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 2 decimals)<br/><br/>
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.000}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 3 decimals) <br/><br/>
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.0000}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 4 decimals)
</apex:page>
Output:
Public class RestrictDecimalPlaces {
public decimal weight {get;set;}
public RestrictDecimalPlaces () {
weight = 50.6789;
}
}
Visualforce Page:
<apex:page controller="RestrictDecimalPlaces">
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.0}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 1 decimals)<br/><br/>
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.00}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 2 decimals)<br/><br/>
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.000}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 3 decimals) <br/><br/>
Weight is :<apex:outputText value="{0, number, ###,###,###,##0.0000}"><apex:param value="{!weight}" /></apex:outputText>(Restricting to 4 decimals)
</apex:page>
Output:
Sunday, December 6, 2015
HelpText to a field in visualforce Page.
With the help of "helpText" attribute of <apex:pageBlockSectionItem> tag, we can provide helptext to a field
Visualforce Page:
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="My Content" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:pageBlockSectionItem helpText="Name of Account">
<apex:outputLabel value="Account Name" for="account__name"/>
<apex:inputText value="{!account.name}" id="account__name"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem helpText="SIte associated with this Account">
<apex:outputLabel value="Account Site" for="account__site"/>
<apex:inputText value="{!account.site}" id="account__site"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Type" for="account__type"/>
<apex:inputText value="{!account.type}" id="account__type"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Number" for="account__number"/>
<apex:inputText value="{!account.accountNumber}" id="account__number"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
Visualforce Page:
<apex:page standardController="Account">
<apex:form>
<apex:pageBlock title="My Content" mode="edit">
<apex:pageBlockButtons>
<apex:commandButton action="{!save}" value="Save"/>
</apex:pageBlockButtons>
<apex:pageBlockSection title="My Content Section" columns="2">
<apex:pageBlockSectionItem helpText="Name of Account">
<apex:outputLabel value="Account Name" for="account__name"/>
<apex:inputText value="{!account.name}" id="account__name"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem helpText="SIte associated with this Account">
<apex:outputLabel value="Account Site" for="account__site"/>
<apex:inputText value="{!account.site}" id="account__site"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Type" for="account__type"/>
<apex:inputText value="{!account.type}" id="account__type"/>
</apex:pageBlockSectionItem>
<apex:pageBlockSectionItem>
<apex:outputLabel value="Account Number" for="account__number"/>
<apex:inputText value="{!account.accountNumber}" id="account__number"/>
</apex:pageBlockSectionItem>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>
Output:
Saturday, December 5, 2015
How to open in new tab after executing PageReference method Salesforce
Apex Code:
public class PageReferenceRedirect {
public pageReference Redirect() {
PageReference pageRef = new PageReference('http://www.google.com');
pageRef.setRedirect(true);
return pageRef;
}
}
Visualforce Page:
<apex:page controller="PageReferenceRedirect" >
<apex:form >
<apex:pageblock > Here underline is removed from Command Link Button.
<apex:commandlink action="{!Redirect}" target="_blank" style="text-decoration: none;">
<apex:commandButton value="Redirect"/>
</apex:commandLink>
</apex:pageblock>
</apex:form>
</apex:page>
Output:
public class PageReferenceRedirect {
public pageReference Redirect() {
PageReference pageRef = new PageReference('http://www.google.com');
pageRef.setRedirect(true);
return pageRef;
}
}
Visualforce Page:
<apex:page controller="PageReferenceRedirect" >
<apex:form >
<apex:pageblock > Here underline is removed from Command Link Button.
<apex:commandlink action="{!Redirect}" target="_blank" style="text-decoration: none;">
<apex:commandButton value="Redirect"/>
</apex:commandLink>
</apex:pageblock>
</apex:form>
</apex:page>
Output:
Remove underline from CommandLink Salesforce
By using the below style in commandLink tag,We can remove underLine.
style="text-decoration: none;"
Visualforce Page:
<apex:page >
<apex:form >
<apex:commandLink > With UnderLine From Command Link </apex:commandLink> <br/><br/>
<apex:commandLink style="text-decoration: none;"> Without UnderLine From Command Link </apex:commandLink>
</apex:form>
</apex:page>
Output:
style="text-decoration: none;"
Visualforce Page:
<apex:page >
<apex:form >
<apex:commandLink > With UnderLine From Command Link </apex:commandLink> <br/><br/>
<apex:commandLink style="text-decoration: none;"> Without UnderLine From Command Link </apex:commandLink>
</apex:form>
</apex:page>
Output:
Salesforce Interview Questions
1) What is the advantage of using custom setting?
Ans:You donot have to query in apex(fire select query) to retrieve the data stored in custom settings.
2) what is whoid and whatid in activities?
Ans:Whoid is the id of either contact or lead.Whatid is the id of the related to record in activiity record(standard or custom object).
3) what is the difference between a standard controller and custom controller?
standard controller inherits all the standard object properties,standard button functionalities can be directly used.Custom controller defines custom functionalities,a standard controller can be extended to develop custom functionalities using keyword "extensions".
4) Can you have more than one extension associated with a single page?
Ans:Yes we can have more than one extension.
5) If page is having extensions and if two extensions have methods of same name.Then which method out of these two will be called from vf page?
Ans:The one which is present in the controller defined on the left side will be called.
6) What are governer limits?
Ans:Governer limits are the limits impossed by salesforce so as to avoid monopoly by orgs in using salesforce shared resources.
7) What is the difference between force.com and salesforce.com?
Ans:force.com is paas(platform as a service) and salesforce.com is Saas(Software as a service)
8) How many records can a select query return?
Ans:As of now,it can return upto 50000 records.
9) How many records can a sosl query return?
Ans:As of now it can return upto 2000 records.
10) How can you access custom label in visualforce page?
Ans:Use this syntax for accessing custom label in visualforce page - {!Label.LabelName} where LabelName is the name of Label.
11) How can you query all records(including deleted records) using an SOQL query?
Ans:Using ALL Rows Keyword.This will query all records including deleted records in recyclebin.
Eg:List <Account> accountList = [select id from account ALL ROWS];
12) What is the use of @future annotation?
Ans: Using @future annotation with a method executes it whenever salesforce has resources available.
13) what is the significance of static keyword?
Ans:Methods,variables when defined as static are initialized only once when class is loaded.Static variables are not transmitted as part of view state for a visualforce page
14) Can custom setting be accessed in a test class?
Ans:Custom setting data is not available default in a test class.We have to set seeAllData parameter true while defining a test class as below
@isTest(seeAlldata=true).
15) what is the difference between role and profile?
Ans:Role defines record level access while profile defines object level access.
16) what is the maximum file size for a generated PDF file?
Ans:The maximum file size for a generated PDF file is 60 MB.
Visualforce PDF Rendering Considerations and Limitations:Go through the below link
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_considerations.htm
Ans:You donot have to query in apex(fire select query) to retrieve the data stored in custom settings.
2) what is whoid and whatid in activities?
Ans:Whoid is the id of either contact or lead.Whatid is the id of the related to record in activiity record(standard or custom object).
3) what is the difference between a standard controller and custom controller?
standard controller inherits all the standard object properties,standard button functionalities can be directly used.Custom controller defines custom functionalities,a standard controller can be extended to develop custom functionalities using keyword "extensions".
4) Can you have more than one extension associated with a single page?
Ans:Yes we can have more than one extension.
5) If page is having extensions and if two extensions have methods of same name.Then which method out of these two will be called from vf page?
Ans:The one which is present in the controller defined on the left side will be called.
6) What are governer limits?
Ans:Governer limits are the limits impossed by salesforce so as to avoid monopoly by orgs in using salesforce shared resources.
7) What is the difference between force.com and salesforce.com?
Ans:force.com is paas(platform as a service) and salesforce.com is Saas(Software as a service)
8) How many records can a select query return?
Ans:As of now,it can return upto 50000 records.
9) How many records can a sosl query return?
Ans:As of now it can return upto 2000 records.
10) How can you access custom label in visualforce page?
Ans:Use this syntax for accessing custom label in visualforce page - {!Label.LabelName} where LabelName is the name of Label.
11) How can you query all records(including deleted records) using an SOQL query?
Ans:Using ALL Rows Keyword.This will query all records including deleted records in recyclebin.
Eg:List <Account> accountList = [select id from account ALL ROWS];
12) What is the use of @future annotation?
Ans: Using @future annotation with a method executes it whenever salesforce has resources available.
13) what is the significance of static keyword?
Ans:Methods,variables when defined as static are initialized only once when class is loaded.Static variables are not transmitted as part of view state for a visualforce page
14) Can custom setting be accessed in a test class?
Ans:Custom setting data is not available default in a test class.We have to set seeAllData parameter true while defining a test class as below
@isTest(seeAlldata=true).
15) what is the difference between role and profile?
Ans:Role defines record level access while profile defines object level access.
16) what is the maximum file size for a generated PDF file?
Ans:The maximum file size for a generated PDF file is 60 MB.
Visualforce PDF Rendering Considerations and Limitations:Go through the below link
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_output_pdf_considerations.htm
How to create custom Links in salesforce
Step 1: Go to setup --> Home --> Custom Links --> click on "New" Button --> Fill the details
Then click "save".
Step 2:Go to setup --> Home --> Home Page Components --> click on "New" Button --> Give Name and select Type as Links
Then click "Next" -->Add to link which is to be displayed
Then click "Save".
Step 3:Go to setup -->Home --> Home Page Layout --> select particular layout by clicking Edit next to it
Search for created Home page Component(here Accounts Tab) and check that checkbox --> Next --> Order the components
Then click on "Save".
Step 4:Go to Home Tab --> Here you find the link.
Once it is clicked it will redirect to custom Link url which we provided.
Step 2:Go to setup --> Home --> Home Page Components --> click on "New" Button --> Give Name and select Type as Links
Then click "Next" -->Add to link which is to be displayed
Then click "Save".
Step 3:Go to setup -->Home --> Home Page Layout --> select particular layout by clicking Edit next to it
Search for created Home page Component(here Accounts Tab) and check that checkbox --> Next --> Order the components
Then click on "Save".
Step 4:Go to Home Tab --> Here you find the link.
Once it is clicked it will redirect to custom Link url which we provided.
Wednesday, December 2, 2015
Split function in Salesforce
Code:
string alphabets='A:B:C';
Splitting the above string with ":" (colon character)
List <String> strList = new List <String>();
strList = alphabets.split(':');
system.debug('Array '+strList );
system.debug('Alphabets :'+strList[0]);
system.debug('Alphabets'+strList[1]);
system.debug('Alphabets'+strList[2]);
Output:
string alphabets='A:B:C';
Splitting the above string with ":" (colon character)
List <String> strList = new List <String>();
strList = alphabets.split(':');
system.debug('Array '+strList );
system.debug('Alphabets :'+strList[0]);
system.debug('Alphabets'+strList[1]);
system.debug('Alphabets'+strList[2]);
Output:
Tuesday, December 1, 2015
Friday, November 27, 2015
Error: Compile Error: Constructor not defined: [SObject].()
problem:
public class SobjectConstructor {
public SobjectConstructor () {
Sobject sobj = new Sobject();
}
}
When we save above piece of code, We get the error.
Solution:We cannot directly create an instance of sobject.First we need to create instance of object(salesforce standard or custom object) and then type cast to sobject
Modify the piece of code like this.
public class SobjectConstructor {
public SobjectConstructor () {
Account acc = new Account();
Sobject sobj = (Sobject) acc;
}
}
public class SobjectConstructor {
public SobjectConstructor () {
Sobject sobj = new Sobject();
}
}
When we save above piece of code, We get the error.
Solution:We cannot directly create an instance of sobject.First we need to create instance of object(salesforce standard or custom object) and then type cast to sobject
Modify the piece of code like this.
public class SobjectConstructor {
public SobjectConstructor () {
Account acc = new Account();
Sobject sobj = (Sobject) acc;
}
}
Subscribe to:
Posts (Atom)
-
How to retrieve validation rules using package.xml in vs code salesforce - Salesforce Globe For You Problem : Assume a validation Mobile_...
-
Assume AccountPage is an apex class in salesforce. Sample Xml file : <?xml version="1.0" encoding="UTF-8"?> ...