Sunday, 22 February 2015

Defining Templates with apex:composition , apex:define and apex:insert



<apex:composition> 

An area of a page that includes content from a second template page. Template pages are Visualforce pages that include one or more <apex:insert> components. The <apex:composition> component names the associated template, and provides body for the template's <apex:insert> components with matching <apex:define> components. Any content outside of an <apex:composition> component is not rendered.

<apex:define> 

A template component that provides content for an <apex:insert> component defined in a Visualforce template page.

<apex:insert> 

A template component that declares a named area that must be defined by an <apex:define > component in another Visualforce page. Use this component with the <apex:composition > and  <apex:define > components to share data between multiple pages.


NOTE:-  
1) All templates defined using <apex:composition> must have one or more child <apex:insert> tags. 
2) An <apex:insert> tag indicates to pages that import the template that a section needs a definition. 
3) Any Visualforce page that imports a template using <apex:composition> must use <apex:define> to specify the content of each <apex:insert> section of the template.

The <apex:composition> component fetches the Visualforce template page you created earlier, and the <apex:define> component fills the named holes in that template. You can create multiple pages that use the same component, and just vary the placeholder text

Example 1 :- simple example 

   Composition page

<apex:page>
    <apex:outputText value="(template) This is before the header"/><br/>
    <apex:insert name="header"/><br/>
    <apex:outputText value="(template) This is between the header and body"/><br/>
    <apex:insert name="body"/>
</apex:page>

   Main Page

<apex:page>
    <apex:composition template="composition">
        <apex:define name="header">(page) This is the header of mypage</apex:define>
        <apex:define name="body">(page) This is the body of mypage</apex:define>
    </apex:composition>
</apex:page>

HTML Output

(template) This is before the header<br/>
(page) This is the header of mypage<br/>
(template) This is between the header and body<br/>
(page) This is the body of mypage


Example 2 :- With controller 

Template VF page
<apex:page controller="compositionExample">
    <h1 style="color:Red"><apex:insert name="Title" /></h1>
    <BR> </BR>
    <BR> </BR>
<apex:form >
    <apex:outputLabel value="First Name: " for="nameField"/>
    <apex:inputText id="nameField" value="{!FirstName}"/>
    <br/>        <br/>

    <apex:insert name="LastNameSection" />
    <br/>        <br/>

    <apex:insert name="AgeSection" />
    <br/>        <br/>

    <apex:commandButton action="{!save}" value="Save" id="saveButton"/>
</apex:form>
</apex:page>

Controller class
public class compositionExample{
    public String FirstName{get;set;}
    public String LastName{get;set;}
    public String Age{get;set;}
    public String colorField {get;set;}
    
    public compositionExample()
    {
    }
    
    public PageReference save() {
        return null;
    }
    
}

Import Template in VF page
<apex:page controller="compositionExample">
 <apex:messages />

  <apex:composition template="myCompositionForm">
     <apex:define name="Title">How to write templates In Visual Force page
     </apex:define>
     
    <apex:define name="LastNameSection">
        <apex:outputLabel value="Last Name: " for="LastName"/>
        <apex:inputText id="mealField" value="{!LastName}"/>
    </apex:define>
    
    <apex:define name="AgeSection">
        <apex:outputLabel value="Age: " for="Age"/>
        <apex:inputText id="ageField" value="{!Age}"/>
    </apex:define>
    
       <apex:outputLabel value=" Color: " for="colorField"/>
       <apex:inputText id="colorField" value="{!colorField}"/>
  </apex:composition>

</apex:page>

Example 3 :- Dynamic Template

Template VF page
<apex:page>
    <apex:insert name="name" />
</apex:page>

Controller class with pageReference which will return template Name
public class dynamicComposition {
    public PageReference getmyTemplate() {
        return Page.myTemplatePage;
    }
}

Import Template in Vf page dynamic y.
<apex:page controller="dynamicComposition">
    <apex:composition template="{!myTemplate}">
    <apex:define name="name">
        Hello {!$User.FirstName}
    </apex:define>
    </apex:composition>
</apex:page>


Thanks,

Amit Chaudhary

Monday, 16 February 2015

StartTest and stopTest Method


StartTest() 

Marks the point in your test code when your test actually begins. Use this method when you are testing governor limits.

public static Void startTest()

StopTest() 

Marks the point in your test code when your test ends. Use this method in conjunction with the startTest method.

public static Void stopTest()

NOTE :-

1) The startTest method marks the point in your test code when your test actually begins. Each test method is allowed to call this method only once
2) All of the code before this method should be used to initialize variables, populate data structures, and so on, allowing you to set up everything you need to run your test. 
3) Any code that executes after the call to startTest and before stopTest is assigned a new set of governor limits.
4) The startTest method does not refresh the context of the test: it adds a context to your test. For example, if your class makes 98 SOQL queries before it calls startTest, and the first significant statement after startTest is a DML statement, the program can now make an additional 100 queries. Once stopTest is called, however, the program goes back into the original context, and can only make 2 additional SOQL queries before reaching the limit of 100
5) All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously

Sunday, 15 February 2015

Future Methods in Salesforce


A future method runs in the background, asynchronously. You can call a future method for executing long-running operations, such as callouts to external Web services or any operation you’d like to run in its own thread, on its own time. You can also make use of future methods to isolate DML operations on different sObject types to prevent the mixed DML error. Each future method is queued and executes when system resources become available. That way, the execution of your code doesn’t have to wait for the completion of a long-running operation. A benefit of using future methods is that some governor limits are higher, such as SOQL query limits and heap size limits

To define a future method, simply annotate it with the future annotation, as follows:-

global class FutureClass
{
    @future
    public static void myFutureMethod()
    {   
         // Perform some operations
    }
}

NOTE :-

1) Methods with the future annotation must be static methods
2) can only return a void type
3) The specified parameters must be primitive data types, arrays of primitive data types, or collections of primitive data types
4) Methods with the future annotation cannot take sObjects or objects as arguments.
5) You can invoke future methods the same way you invoke any other method. However, a future method can’t invoke another future method
6) No more than 50 method calls per Apex invocation
7) Asynchronous calls, such as @future or executeBatch, called in a startTest, stopTest block, do not count against your limits for the number of queued jobs
8) The maximum number of future method invocations per a 24-hour period is 250,000 or the number of user licenses in your organization multiplied by 200, whichever is greater
9) To test methods defined with the future annotation, call the class containing the method in a startTest(), stopTest() code block. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously


IMP:-
The reason why sObjects can’t be passed as arguments to future methods is because the sObject might change between the time you call the method and the time it executes. In this case, the future method will get the old sObject values and might overwrite them.  To work with sObjects that already exist in the database, pass the sObject ID instead (or collection of IDs) and use the ID to perform a query for the most up-to-date record. The following example shows how to do so with a list of IDs


Example of a future method that makes a callout to an external service. Notice that the annotation takes an extra parameter (callout=true) to indicate that callouts are allowed

global class FutureMethodExample
{
    @future(callout=true)
    public static void getStockQuotes(String acctName)
    {   
         // Perform a callout to an external service
    }

}


Future Method Considerations

  • Remember that any method using the future annotation requires special consideration because the method does not necessarily execute in the same order it is called.
  • Methods with the future annotation cannot be used in Visualforce controllers in either getMethodName or setMethodName methods, nor in the constructor.
  • You cannot call a method annotated with future from a method that also has the future annotation. Nor can you call a trigger from an annotated method that calls another annotated method.
  • The getContent and getContentAsPDFPageReference methods cannot be used in methods with the future annotation

Thanks,
Amit Chaudhary

Wednesday, 11 February 2015

Progress Bar/Loading Image on Visualforce Page by ActionStatus Tag in Salesforce


Some time we need to show some loading image or progress bar while we are doing some progress or calculation on page. In that case we can use <apex:actionStatus> tag to show loading image


<apex:page >
<apex:form >
    <apex:pageBlock id="PB1">
        <apex:pageBlockSection >
            <apex:commandButton status="waitStatus" value="Load Image" reRender="PB1"/>
        </apex:pageBlockSection>
    </apex:pageBlock>
<apex:actionStatus id="waitStatus" style="align:center;">      
            <apex:facet name="start">
                 <apex:image value="/img/loading.gif" title="Processing..."/>
             </apex:facet>
            <apex:facet name="stop"></apex:facet>
</apex:actionStatus>
</apex:form>
</apex:page>

Friday, 6 February 2015

Field Sets



A field set is a grouping of fields. For example, you could have a field set that contains fields describing a user's first name, middle name, last name, and business title. Field sets can be referenced on Visualforce pages dynamically. If the page is added to a managed package, administrators can add, remove, or reorder fields in a field set to modify the fields presented on the Visualforce page without modifying any code.

Step 1: Create Field set in Account Object.

Setup->Customize->Account->Field Sets
Drag and Drop the fields required for the Field Set

Step 2: Create Visual Force Page


 <apex:repeat value="{!lstAccount}" var="acc"> 
 <table width="100%">
   <apex:repeat value="{!$ObjectType.Account.FieldSets.Account_FieldSet}" var="fieldSet"> 
     <tr> 
      <td>
        {!fieldSet.Label}
      </td>   
      <td>
       <apex:inputField value="{!acc[fieldSet]}"/>
      </td>
      </tr>   
       </apex:repeat>
      </table>
</apex:repeat>

Step 3: Write the Controller for the VisualForce Page

public with sharing class DynamicTabController 
{     public List<Account> lstAccount{get;set;}          public DynamicTabController()     {         lstAccount=new List<Account>();                 String query = 'SELECT ';                 for(Schema.FieldSetMember f : this.getFields())                  {                     query += f.getFieldPath() + ', ';                 }                 query += '  Id FROM Account limit 5 ';                 System.debug('query ------>'+query );                 lstAccount = Database.query(query);             }     public List<Schema.FieldSetMember> getFields()      {         return SObjectType.Account.FieldSets.Account_FieldSet.getFields();     } }

Thanks,
Amit Chaudhary

How is Visualforce Architected


All Visualforce pages run entirely on the Force.com platform, both when a developer creates the page, and when an end user requests a page, as shown in the following architecture diagrams





When a developer finishes writing a Visualforce page and saves it to the platform, the platform application server attempts to compile the markup into an abstract set of instructions that can be understood by the Visualforce renderer. If compilation generates errors, the save is aborted and the errors are returned to the developer. Otherwise, the instructions are saved to the metadata repository and sent to the Visualforce renderer. The renderer turns the instructions into HTML and then refreshes the developer's view, thereby providing instantaneous feedback to the developer for whatever changes were made in the markup.

The architecture diagram below shows the process flow when a non-developer user requests a Visualforce page. Because the page is already compiled into instructions, the application server simply retrieves the page from the metadata repository and sends it to the Visualforce renderer for conversion into HTML.