Wednesday, 3 April 2013

Dynamic Field Binding in Salesforce


This tip is useful when we are going to display different field for different users.We can avoid non empty field from displaying in visualforce page by using rendered property.   We can write  rendered="{!IF(NOT(ISNULL(Field)),true,false)}". If field has some value then condition becomes true , that means rendered is true . So field is displayed .  Its a simple one , then  what is the use of this tip ...?
 Suppose we have 20 fields in an object and an user wants to display those fields which has some value . So we will do easily using rendered property . But we have to write rendered property in every field . is not this a clumsy one...?  We always write short code satisfying our requirement . what If we use that rendered property only once to solve our requirement. is not it easy...? Here is my page code...
 
<apex:page controller="Renderfieldcontroller">
  <apex:form >
    <apex:pageBlock >
       <apex:pageBlockSection columns="2" title="Book Information" rendered="{!Enable!='show'}">
      
          <apex:repeat value="{!threeFieldList}" var="afield" >

              <apex:inputField value="{!Book[afield]}"  />
          </apex:repeat><br/>
         
          <apex:commandButton value="Save" action="{!savingBook}"/>
      
       </apex:pageBlockSection>
      
       <apex:pageBlockSection columns="2" title="Book Information" rendered="{!Enable=='show'}">
     
          <apex:repeat value="{!threeFieldList}" var="afield" >

              <apex:outputField value="{!Book[afield]}" rendered="{!IF(NOT(ISNULL(Book[afield])),true,false)}"  />
          </apex:repeat><br/>
       </apex:pageBlockSection>
      
    </apex:pageBlock>
    </apex:form>
    </apex:page>
 
Now My controller......
 
public class Renderfieldcontroller {

   List<string>threeFieldList{get; set;}
   public final Book__c bok{get;set;}
   public String Enable{get;set;}

   public Renderfieldcontroller () {
      bok = new Book__c ();
      if (threeFieldList == null) {

             threeFieldList = new List<String>();
             threeFieldList.add('Author__c');
             threeFieldList.add('Price__c');
             threeFieldList.add('Publisher__c');
             threeFieldList.add('Title__c');
               
        }

      }
     
    public List<String> getthreeFieldList() {
        return threeFieldList;
     }
        
    public Book__c getBook() {
       return bok;
     }
         
    public PageReference savingBook() {
         upsert bok;
         Enable = 'show';
         return null;
     }
  }
 

No comments: