Saturday, June 14, 2014

View All the Account Related Contacts in single VF page.


Hi,

I have one requirement that like Actvities Viewall functionality my client is asking me to display all the contact's in a single page. for example:-

Go to Account's Tab and click on account -->go to Activity History Related list and click on View all button.


Once you click on "View All" button it open a page with all the Activities.



like that we need to display a page with all the contact's of that account. to achieve for this we develop a VF page and Command link button.

Go to setup-> customize-> Contact->Buttons Links-> Create a  "New Button Link" like in the below screen shot.

save image
save image

once you create a button place the button in related list. and develop a VF page name as "Showallcontacts" 
save image

VF Page :

<apex:page controller="ShowAllContact" tabStyle="Account">
  <apex:form >
     <apex:sectionHeader title="Contact Details"/>
       
                 <center><apex:commandButton value="cancel" action="{!cancel}" /></center>
       
   <apex:repeat value="{!contlist}" var="c">
    <apex:pageBlock >
        <apex:pageBlockSection columns="1" >
            <apex:outputField value="{!c.FirstName}" />
            <apex:outputText value="{!c.LastName}" />
        </apex:pageBlockSection>
      </apex:pageBlock>
     
   </apex:repeat>
  <center><apex:commandButton value="cancel" action="{!cancel}" /></center>
  </apex:form>

</apex:page>


Controller Class:

public class ShowAllContact {

 string accid= ApexPages.currentPage().getParameters().get('accid');


public list<Contact> contlist{get;set;}

public ShowAllContact(){
  if(accid !=null )
  //contlist= [select id,firstname,lastname,phone,email from contact where accountid='0019000000wFr7E'];
  contlist= [select id,firstname,lastname,phone,email from contact where accountid=:accid];
  }
 
      public PageReference cancel() {
      URL currentURL = URL.getCurrentRequestUrl();
      system.debug('currentURL.getPath()->'+currentURL.getPath());
      account acc = new account();
       // Send the user to the detail page for the new account.
        PageReference acctPage = new PageReference('/'+accid);
        acctPage.setRedirect(true);
       
        return acctPage;

       
    }
   
}



once you develop all the code you can view all the contacts for an Account like this.

save image


 That's it.....
Enjoy






Fetch the Label Value using Salesforce Apex Class and Visualforce Page?

Fetch the Label Value using Salesforce Apex Class and Visualforce Page?


Custom labels are custom text values that can be accessed from Apex classes or Visualforce pages. Yes, we can fetch the Label Value both apex class and visualforce page

first create a Label using below path:

Setup-> App Setup-> Create-> Custom Labels
Create new label Called ‘Event Title’ and use the below code.

Apex Class:

String printLabel = Label.Event_Title;
system.debug(‘printLabel::’+printLabel);


Visualforce Page:

<apex:sectionHeader title=”{!$Label.Event_Title}” />


Note : we can create up to 5,000 custom labels and they can be up to 1,000 characters in length.

https://help.salesforce.com/htviewhelpdoc?id=cl_about.htm&siteLang=en_US





Friday, June 13, 2014

Enforcing field level security using Salesforce Apex Class?

You can determine field level security by using getDescribe() . Below is the example.

Schema.DescribeFieldResult fieldld = Account.Phone.getDescribe();
Boolean notHidden  = fieldld.isAccessible();
Boolean notReadonly = fieldld.isUpdateable(); 


Thursday, June 12, 2014

How to convert from sObject to String using Salesforce Apex Class?

How to convert from sObject to String using Salesforce Apex Class?


To convert sObject to String in Apex, below i s the example,

Example:
public sObject searchContact;
String strObjType = String.valueOf(searchContact);





Wednesday, June 11, 2014

Adding Error Message in the Visualforce page through Apex controller.

Adding Error Message in the Visualforce page through Apex controller.

Hi,

In this post i am giving an example of how to add error message in controller and display in VF Page.

Syntax : <apex:pageMessages ></apex:pageMessages>

Apex Controller:


public class ErrorMsgController {
public void DisplayError(){
Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Required fields are missing. ')); //FATAL, WARNING, INFO, CONFIRM
}
}


VF Page:

<apex:page sidebar="false" showHeader="false" controller="ErrorMsgController">
<apex:form >
<apex:pageMessages ></apex:pageMessages>
<apex:commandButton value="Click" action="{!DisplayError}"/>
</apex:form>
</apex:page>








Tuesday, June 10, 2014

Sending Email with Attachment using Apex class and Visualforce page?

Sending Email with Attachment using Apex class and Visualforce page?


Hi,
In this post i am giving an Example of creating an email attachment from Apex class for a particular case.

VF Page:

<apex:page controller="SendemailController">
<apex:form >
<script type="text/javascript">
function init() {
sendEmail();
}
if(window.addEventListener)
window.addEventListener('load',init,true)
else
window.attachEvent('onload',init)
</script>

<apex:actionFunction name="sendEmail" action="{!sendEmailFunction}">
</apex:actionFunction>
</apex:form>
</apex:page>

Controller Class:-

public class SendemailController { public String caseId {get;set;} Public SendemailController(){ caseId = ApexPages.currentPage().getParameters().get('Id'); system.debug('case id->'+caseId ); } Public Pagereference sendEmailFunction(){ Case getEmail = [SELECT Id, Contact.Email FROM Case WHERE id=:caseId]; if(getEmail.Contact.Email != null) { String toaddress = getEmail.Contact.Email; try { Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); String[] toAddresses = new String[] {toaddress}; String[] ccAddresses = new String[] {'sfdcsrini@gmail.com'}; mail.setToAddresses(toAddresses); mail.setCcAddresses(ccAddresses); mail.setReplyTo(toaddress); mail.setSenderDisplayName('Name'); mail.setSubject('Testing email through apex'); mail.setBccSender(false); mail.setUseSignature(true); mail.setPlainTextBody('This is test email body. This mail is being sent from apex code'); //mail.setHtmlBody('<b> This is HTML body </b>' ); List<Messaging.Emailfileattachment> fileAttachments = new List<Messaging.Emailfileattachment>(); for (Attachment a : [select Name, Body, BodyLength from Attachment where ParentId = :caseId]){ Messaging.Emailfileattachment efa = new Messaging.Emailfileattachment(); efa.setFileName(a.Name); efa.setBody(a.Body); fileAttachments.add(efa); //mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa}); } mail.setFileAttachments(fileAttachments); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } catch(Exception e) {} } PageReference reference = new PageReference('https://na15.salesforce.com/'+caseId); reference.setRedirect(true); return reference; } }
Once you call this VF page with this url
 "https://c.na15.visual.force.com/apex/SendingEmailVF?id=500i0000004hcM 
then it is going to send email to the address that you specified in mail.setToAddresses(toAddresses) in apex class.

Sunday, June 8, 2014

Ajax implementation with ActionStatus in visualforce page?

 Ajax implementation with ActionStatus in visualforce page?



Visualforce Page:

<apex:page controller="exampleCon">
<apex:form >
<apex:outputText value="Watch this counter: {!count}" id="counter"/>
<apex:actionStatus startText=" (incrementing…)" stopText=" (done)" id="counterStatus" />
<apex:actionPoller action="{!incrementCounter}" rerender="counter" status="counterStatus" interval="05"/>
</apex:form>
</apex:page>

Apex Class Controller:

public class exampleCon {
Integer count = 0;

public PageReference incrementCounter() {
count++;
return null;
}

public Integer getCount() {
return count;
}
}





if you want to decrease the time interval just set the interval="05" and test.

Please use the below snippets code to show the status  by image.

<apex:actionStatus id=”counterStatus” >
<apex:facet name=”start” >
<apex:image url=”{!$Resource.LoadingImage}” />
</apex:facet>
</apex:actionStatus>








Saturday, June 7, 2014

How to get the Case Number using ThreadID from Apex Class?

How to get the Case Number using ThreadID from Apex Class?


Using ThreadID, we can get the relevant Case Number using “getCaseIdFromEmailThreadId” method. see the below example for your reference:

String emailThreadId = ’00DD0CG3j._500D0ZaQLq’;
// Call Apex method to retrieve case ID from email thread ID
ID caseId = Cases.getCaseIdFromEmailThreadId(emailThreadId);
system.debug(‘caseId:::’ + caseId);

Same way we can prepopulate the Case ThreadID using formula fields,

Here ThreadID is nothing but its a combination of Your Salesforce ORG ID and Case ID.







What is system.limitexception: Apex heap size too large ?

What is system.limitexception:Apex heap size too large ?


You have probably seen this error before while doing some heavy lifting in Apex.  If you are wondering how you got this error and how to remedy it, fear not, I will be outlining a number of simple changes that can help aid in fixing this error.

First of all, what does it mean when you hit this limit?  It essentially means you are using too much memory.  Since Salesforce is a shared tenant system, there are limits put in place so you do not use too much of any resource, memory being one of them.  So to get around this error you need to be cognizant of your memory and how you are using it.

I have seen a number of people suggesting that declaring variables as transient will fix the heap size error but declaring a variable as transient is more just a way of decreasing the size of the ViewState on a VisualForce page that is using apex:forms.  While it may have an effect, the effect would be insignificant and this is not normally the culprit for these types of errors.

From what I have seen, the biggest issue with heap size comes from querying an object outside of the scope of a loop.  After this query the code will still iterate over that object to perform some sort of logic for variable placement, wrapper class built, etc.  To get around this, put your queries in the loop.  Below is an example of what not to do with the subsequent what to do.  Feel free to run this code in an anonymous window to see for yourself the heap size difference between the two.

//Don't do this…
List<Account> accountList = [Select Id, Name FROM Account LIMIT 5000];
System.debug(LoggingLevel.ERROR, 'Heap Size: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());      
Map<Id, String> accountMap = new Map<Id, String>();
for(Account a : accountList){
    accountMap.put(a.Id, a.Name);
}
System.debug(LoggingLevel.ERROR, 'Heap Size: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());      


//This is much better
System.debug(LoggingLevel.ERROR, 'Heap Size: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());      
Map<Id, String> accountMap = new Map<Id, String>();
for(Account a : [Select Id, Name FROM Account LIMIT 5000]){
    accountMap.put(a.Id, a.Name);
}

System.debug(LoggingLevel.ERROR, 'Heap Size: ' + Limits.getHeapSize() + '/' + Limits.getLimitHeapSize());      


Another pitfall comes from simply querying more fields than you need to from the object.  The more fields, the more memory you will need to store those fields.  So when you are building your queries, be sure to only grab what you need.

Another less common issue comes from lists and how you build them.  This is especially prevalent when using recursion.  For an example, let’s assume that you are building a text string from a tree type structure.  As you are iterating through the structure to build the string you need to call the same method from within the method.  This is all well and good until you start adding more and more to the lists after you have already used them.  A good way to get around this is to remove or null the specific instance of the object when you are done with it. 

//Recursive example that removes objects when done
public String myRecursiveMethod(List<MyObject> myList){
    String myText = '';
    Integer size = myList.size();
    for(Integer i = 0; i < size; i++){
        if(myList.get(0) != null){
            myText += myRecursiveMethod(myList.get(0));
        }  
        myList.remove(0);
    }
    return myText;
}


//Another example of nulling objects when done
for(MyObject mo : myObjectList){
    doStuffWithMyObject(mo);
    mo = null; 
}

I hope these options will help you get around this error.  For the most part your issues are going to come from one of the above situations but there are some edge cases.  I’ll leave you with something you should not do—Do not call recursive methods from within a debug statement!





Friday, June 6, 2014

How to get the Salesforce Instance Server URL from APEX Trigger?

How to get the Salesforce Instance Server URL from APEX Trigger?


Hi,

Using trigger we can get the Salesforce Server URL, below is the example:

for example, used below codes in before insert or before update triggers from account object,

trigger accountBeforeInsert on Account (before insert, before update) {
if(trigger.isBefore == true && (trigger.isInsert == true || trigger.isUpdate == true)) {
URL currentURL = URL.getCurrentRequestUrl();
URL comparisonURL = new URL(URL.getSalesforceBaseUrl().toExternalForm() + Page.YOUR_VF_PAGE_URL.getUrl());
system.debug('currentURL:::'+ currentURL);
system.debug('comparisonURL:::'+ comparisonURL);
boolean knownPath = currentURL.getPath() == comparisonURL.getPath();

if(knownPath == true) {
// Currently You comming from Custom VF Page ("YOUR_VF_PAGE_URL")
} else {
// Currently You Comming from Standard Account Page Creation.
}
}
}

Note: if you view and submitting the page from “YOUR_VF_PAGE_URL” then you can get the values true in the “knownPath” variables.
Ex:

https://c.cs8.visual.force.com/apex/YOUR_VF_PAGE_URL?Id=00UL0000001Ytcf

knownPath = TRUE;

if you trying to create a new account from standard page

https://cs8.salesforce.com/001/e?retURL=%2F001%2Fo&nooverride=1

knownPath = FALSE;


That's it !!


Thursday, June 5, 2014

How Insert new case comment using Apex Trigger in salesforce?

How Insert new case comment using Apex Trigger in salesforce?


Hi,
In this post i am trying to give a trigger example of creating case comments while creating case.

Task: I need to insert the CaseComment to all the Relevant Cases whenever New casecommnet is created or updated Using Trigger,

Trigger:

trigger updateCaseComment on CaseComment(after insert, after update) {
Map<Id,CaseComment> caseMap = new Map<Id,CaseComment>();

for (CaseComment t: Trigger.new){

caseMap.put(t.ParentId,t);
}

Set<Id> idSet = caseMap.keySet();
List<Case> allCases = [select Id,ParentId from Case where ParentId in :idSet];
List<CaseComment> childCommand = new List<CaseComment>();

for(integer i=0;i<allCases.size();i++){ 

CaseComment newCommmand = new CaseComment();
newCommmand.CommentBody = caseMap.get(allCases[i].ParentId).CommentBody;
newCommmand.IsPublished = TRUE;
newCommmand.ParentId = allCases[i].id;
childCommand.add(newCommmand);
}

if(!childCommand.isEmpty()){
insert childCommand;
}

}



That's it !!






Wednesday, June 4, 2014

How to execute Batch Apex Using Apex Trigger?

How to execute Batch Apex Using Apex Trigger?

Hi,
In this post i am trying to give an example of how to execute Batch Process from Apex Trigger. Here i am calling Batch class from the trigger.

Trigger:

trigger UpdateAreaInfoUser on User (after update)  {
Map<id, User> owners = new Map<id, User>();

for (Integer i=0;i<Trigger.new.size();i++) {
if (Trigger.new[i].Team__c!=Trigger.old[i].Team__c) {
owners.put(Trigger.new[i].Id, Trigger.new[i]);
}
}

// You can execute batch apex using trigger using below codes
if (owners.size() > 0) {
Database.executeBatch(new UpdateAccountArea(owners));
}

}


Batch Apex Class:

global class UpdateAccountArea implements Database.Batchable<sObject> {
//map of userid - user
Map<Id, User> ownerMap = new Map<Id, User>();

//Constructor initialization
global UpdateAccountArea(Map<Id, User> owners) {
ownerMap = owners;
}

//Quuery method.
global Database.QueryLocator start(Database.BatchableContext BC) {
return DataBase.getQueryLocator([SELECT Id,Area__c, OwnerId FROM account WHERE OwnerId IN : ownerMap.keySet()]);
}

//Execute Method.
global void execute(Database.BatchableContext BC,List<Account> scopeAcc) {

for (Integer i=0;i<scopeAcc.size();i++){
scopeAcc.get(i).Area__c=ownerMap.get(scopeAcc.get(i).OwnerId).Team__c;
}
update scopeAcc;
}

//Finish method to execute at last.
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
String[] toAddresses = new String[] {'sfdcsrini@gmail.com'};
mail.setToAddresses(toAddresses);
mail.setSubject('Apex Batch Job is done');
mail.setPlainTextBody('The batch Apex Job Processed Successfully');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
}
}


That's it !!

Monday, June 2, 2014

How to know Recently Viewed items using Soql Apex Class?

How to  know Recently Viewed items using Soql Apex Class?


In Summer ’13 Release salesforce introduced the new Standard Object called  RecentlyViewed, so using that we can easily get the all the recently viewed items using apex class.
Sample SOQL:
SELECT Id, Name, LastViewedDate FROM RecentlyViewed  WHERE Type IN ('Account', 'Contact', 'Case') ORDER BY LastViewedDate DESC
Note:
The RecentlyViewed object does not support the Report, KnowledgeArticle, and Article objects.





What is the maximum trigger depth exceeded exception in salesforce?

What is the  maximum trigger depth exceeded exception in salesforce?



When you are creating an Apex code that recursively fires triggers due to insert/update/delete statement for more than 16 times. You will get the Maximum Trigger Depth Exceeded error.

The following example will demonstrate this issue:

trigger cloneAnotherAcc on Account (before insert) {
Account acc = new Account(name=’Clone me’);
insert acc;
}

This trigger will end up in an infinite loop.

In order for you to solve this issue, you can set a condition on insert so it will not be called recursively. Set a flag to manage the insert trigger will be the ideal. To do this, you need to create a new class to keep track the number of times of insert or stop the insert process on second time.

global class triggerCount {
static integer runTimes = 0;

public static integer getRunTimes(){
return runTimes;
}

public static void setRunTimes(){
runTimes++;
}
}

Once you successfully create this class, you can implement this triggerCount class on your trigger to limit the number of times for insert.

trigger createAcc on Account (before insert) {
if(triggerCount.getRunTimes < 2){
Account acc= new Account(name=’Clone me’);
triggerCount.setRunTimes();
insert acc;
}
}



 
| ,