Showing posts with label apex. Show all posts
Showing posts with label apex. Show all posts

Friday, May 19, 2017

Instantiation of a Page Reference in Apex, Salesforce

In many cases, after a custom action performed, we may need to redirect the page to a different page, could be another Visualforce page / standard Page like a list view of an object or any of default pages like view / edit page of a record or a new record entry page.

Page redirection happens in Apex code using PageReference class.

There are multiple ways to instantiate a page reference in Apex. Below are list of all possible ways.

Approach 1:
PageReference pageRef = new PageReference('***partialURL***');
PageReference pageRef = new PageReference('***FullURL***');

Eg:

PageReference pageRef = new PageReference('/apex/CustomPage1?id=xxxxxx');
PageReference pageRef = new PageReference('/a04');

PageReference pageRef = new PageReference('http://www.google.com');

Approach 2:
PageReference pageRef = Page.<<VF Page Name>>;

Eg:

PageReference pageRef = Page.CustomPage;
pageRef.getParameters().put('id','XXXXXXX');

Approach 3:
Refer stnadard pages of an Object / record

PageReference pageRef = new ApexPages.StandardController(recordObj).edit();
PageReference pageRef = new ApexPages.StandardController(recordObj).view();

Refer List view of an object

PageReference pageRef = new PageReference('/'+<<Object>>.sObjectType.getDescribe().getKeyPrefix());

PS: Try not to hard code URLs and use above available options to build the URLs.

Friday, April 21, 2017

Display Validation rule Errors on a Visualforce Page

One among the most useful features in Salesforce is Validation rules in an object. With Validation rules, e can provide a formula / conditional check and if it met, we display an error message to end user and thus stopping user from saving the record.  The advantage of validation rules is that it validates records when entered in forms and also through other means like data loader. So, if there are any conditions which are mandatory, better to have them in Validation rules, even though you have custom forms.

A simple example in my application is, we can't allow users to provide weight less than 1 LBS. To accomplish this, we added a validation rule as below.

And, in our application, we are having Visualforce pages for the forms as we have some complex functionalities which can't be accomplished through default layouts.

In order to display errors on forms like mandatory field / invalid value , we simply need to provide a visualforce component / tag "<apex:pagemessages />" in the layout as per our design. By adding this, upon save of an object, if there are any errors in data, they are listed in pagemessages section.

But, Validation rules, don't come under default errors of a data record. They actually through DML Exceptions. So, in order to show the validation errors, in the Apex class save method, we need to catch the  DML exceptions and just provide the exception to Apexpage messages. It parses the error messages and displays them in page messages. Below is sample code.

public class customController
{
    public object__C obj {get;set;}
    
    public customController(ApexPages.StandardController ctlr)
    {
        //Consturctor, define obj here.
    }
    
    public pagereference custommSave()
    {
        try
        {
            upsert obj;
            return new pagereference('/'+obj.id);
        }         
        catch(DmlException ex){
            ApexPages.addMessages(ex);
            return null;
        }
        catch(Exception ex){
            //Handle exception
            return null;
        }
    }
}

Happy coding!

Tuesday, March 17, 2015

Mathematical Operations & Number formatting in Visualforce Page

In a Visualforce page, if we want to do some basic mathematical Operations and display on the screen, eg: display percentage along with the existing value in a Table, we can use apex:outputtext

Sample code to implement it is as below, here we are displaying it in a PageBlockTable, display marks for each subject in one column and  Percentage (Calculated) for each subject in another column

 <apex:pageBlockTable value="{!score}" var="item">  
      <apex:column value="{!item.subject}"/>   
      <apex:column value="{!item.marks}" dir="RTL">  
           <apex:facet name="footer" >  
                {!total}  
           </apex:facet>  
      </apex:column>       
      <apex:column >  
           <apex:outputText value="{!(item.marks / total) * 100}%" />  
      </apex:column>  
 </apex:pageBlockTable>   

In above example, we already have a variable 'total' with sum of marks of all subjects.

In some scenarios, we  might need to format the text when we display on screen like, Currency notation / Date in a specific format etc.. apex:outputtext also has this functionality.

Sample code to implement it is as below, here we send input to outputtext as params, which are used with number notations {0} as in C, C++

 <apex:outputText value="{0, number, 000,000.00}$">  
   <apex:param value="{!AnnualRevenue}" />  
 </apex:outputText>  
  <apex:outputText value="The formatted time right now is:   
       {0,date,yyyy.MM.dd G 'at' HH:mm:ss z}">  
   <apex:param value="{!NOW()}" />  
 </apex:outputText>