Tuesday, January 28, 2014

System admin has created a Visualforce for Account. In future he created few more new Fields. How could System admin can code Visualforce so that in future if any new field is added or existing field deleted. It should reflect in Visualforce without changing anycode

System admin has created a Visualforce for Account. In future he created few more new Fields. How could System admin can code Visualforce so that in future if any new field is added or existing field deleted. It should reflect in Visualforce without changing anycode

It can be done with help of Field Sets. Please read this article.
Case - 1
public class MerchandiseDetails {

    public Merchandise__c merch { get; set; }
   
    public MerchandiseDetails() {
        this.merch = getMerchandise();
    }

    public List<Schema.FieldSetMember> getFields() {
        return SObjectType.Merchandise__c.FieldSets.Dimensions.getFields();
    }

    private Merchandise__c getMerchandise() {
        String query = 'SELECT ';
        for(Schema.FieldSetMember f : this.getFields()) {
            query += f.getFieldPath() + ', ';
        }
        query += 'Id, Name FROM Merchandise__c LIMIT 1';
        return Database.query(query);
    }
}
<apex:page controller="MerchandiseDetails">
    <apex:form >

      <apex:pageBlock title="Product Details">
          <apex:pageBlockSection title="Product">
              <apex:inputField value="{!merch.Name}"/>
          </apex:pageBlockSection>
     
          <apex:pageBlockSection title="Dimensions">
              <apex:repeat value="{!fields}" var="f">
                  <apex:inputField value="{!merch[f.fieldPath]}"
                      required="{!OR(f.required, f.dbrequired)}"/>
              </apex:repeat>
          </apex:pageBlockSection>
 
        </apex:pageBlock>

    </apex:form> 
</apex:page>

Case - 2
<apex:page standardController="Contact">
    <apex:repeat value="{!$ObjectType.Contact.FieldSets.properNames}" var="f">
        <apex:outputText value="{!Contact[f]}" /><br/>
    </apex:repeat>
</apex:page>


No comments:

Post a Comment