Monday 27 June 2011

Adding Columns to PageBlockTable Dynamically.

We have client requirement to add columns dynamically to Page block table,Based on user input,Number of columns to be added,we have to add that columns to table.We tried lot,and my community friend sharma also helped me in this scenario.I will explain this step by step,Actually with dynamic way we can't prioritize columns to add table.That is if you give 5 as input any 5 columns are adding to Table,to avoid that problem we need to place, field name, object Name, field value in custom settings.if user input is 5,then first 5 columns are added in this way.
   1 . Creating Custom Settings.
          Create custom settings and name it as "Custom fields" with fields fields FieldName,FieldValue,Object Name. While creating Custom setting ,Select Settings type as "List" and Visibility as "public".Create records in to custom settings like
              Lastname, 1,Contact
              phone,2,Contact
              Email,3,Contact
              Department,4,Contact.
2.Here Basic concept is dynamic binding the fields.
Here i did, first i query the fields list from custom settings, using describe object methods getting fields labels in to Map(o display headers for Table),Based on user input binding that number of fields from custom settings.

Controller:-

    public class Demo {
    public map<String , String> mapFieldToShow{get;set;}
    public map<String , String> mapFieldToShow1{get;set;}
    list<String> lstfield=new list<String>();
    list<String> lstflabel=new list<String>();
    
    public Integer noOfColumns // User input
    { 
       get; 
       set
         {
    
               listFieldToShow = new List<String>(); 
            // listFieldToShow.addAll(lstField); 
               for(integer i=0;i<value;i++)                          //value is user input.
               listFieldToShow.add(lstFlabel[i]);                // we are binding that number of fields.
    
           } 
    }
    
    public List<String> listFieldToShow {get;set;}
    List<String> fieldLabels=new List<String>();
    public  Demo()
    {        
    Contactfields__c objp=[select objectName__c from Contactfields__c limit 1];
    SObjectType objToken = Schema.getGlobalDescribe().get(objp.objectName__c);      
    DescribeSObjectResult objDef = objToken.getDescribe();                    
    Map<String, SObjectField> fieldmap = objDef.fields.getMap(); 
    for(Contactfields__c obj:[select fieldName__c from Contactfields__c order by Fieldvalue__c]) // query from custom settings.
    lstfield.add(obj.fieldName__c);
    listFieldToShow = new List<String>();
    mapFieldToShow = new Map<String , String>();
    mapFieldToShow1 = new Map<String , String>();
    for(integer i=0;i<lstfield.size();i++){
    SObjectField fieldToken = fieldmap.get(lstfield[i]);
    DescribeFieldResult selectedField = fieldToken.getDescribe(); 
    lstflabel.add(selectedfield.getLabel());
    mapFieldToShow.put(selectedfield.getLabel() ,selectedfield.getLocalName());
    mapFieldToShow1.put(selectedfield.getLabel() ,selectedfield.getLabel());
    }
    
    String squery='select ';                                         // Building Dynamic Query.
    for(integer i=0;i<lstfield.size()-1;i++) 
    squery=squery+''+lstfield[i]+',';
    squery=squery+''+lstfield[lstfield.size()-1];
    squery=squery +' '+'from Contact limit 20';
    System.debug('Squeryyyyyyyy'+squery);
    listTableResult =Database.query(squery); 
    
    
    }
    public List<Contact> listTableResult {
    get;set;
    }
    
    public PageReference Add() 
    {
    
                return ApexPages.currentpage();
    
    }
    public List<Contact> getlistTableResult() {
    
    return listTableResult;
    }
    public void setlistTableResult(List<Contact> Contacts) {
    listTableResult = Contacts;
    
    }
    public PageReference save() {   // to save updates.
    upsert listTableResult;
    return null;
    }
    }



Page:-

<apex:page controller="Demo" tabStyle="Contact">
     <apex:Form >
          <apex:pageBlock >
                <apex:pageBlockButtons >
                    <apex:commandButton action="{!Add}" value="Add"/>
                     <apex:commandButton action="{!save}" value="save"/>
                </apex:pageBlockButtons>  
                <apex:pageBlockSection >
                    <apex:pageBlockSectionItem >
                        <apex:outputLabel value="No of Colums">
                        </apex:outputLabel>
                        <apex:inputText value="{!noOfColumns}" />
                    </apex:pageBlockSectionItem>
                </apex:pageBlockSection>
                <apex:pageBlockSection collapsible="true" title="Adding Columns Dynamically" columns="1">
                         <apex:PageBlockTable columns="{!listFieldToShow.size}" value="{!listTableResult}" var="rowItem">           
                <apex:repeat value="{!listFieldToShow}" var="colItem">
                    <apex:column >
                        <apex:facet name="header" >{!mapFieldToShow1[colItem]}</apex:facet>
                        <apex:inputField value="{!rowItem[mapFieldToShow[colItem]]}"></apex:inputField>
                    </apex:column>
                </apex:repeat>
            </apex:PageBlockTable>
        </apex:pageBlockSection>
          </apex:pageBlock>
     </apex:Form>
</apex:page>








Thursday 9 June 2011

Small URL Trick to fill data into standard user interface of an object.

While we are inserting data for an object from it's standard page, we can do one trick to fill data into page from URL.Actually for this trick we need sales force.com id's for the fields in an object.But we can't get ids for the fields in an object like object id.For this i am taking java script id's for the fields from view source. This trick executes for Names of the standard fields directly,but in case of custom fields we can go for java script id's from view source for that page.
                     i am giving the screen shot just follow the instructions,

        This is standard user interface of an object " Address"  to create new record.Here you need to observe the URL in address bar of the window.
         i.e https://ap1.salesforce.com/a01/e?retURL=%2Fa01%2Fo .     
In the above object NAME is the standard field so just observe the below URL,
        https://ap1.salesforce.com/a01/e?retURL=%2Fa01%2Fo&Name=FLEXANDSALESFORCE
click enter. Then you can observe in the following screen,
       In this way you can pass values to fields from URL.In case of Custom fields this is not works ,but with java script  id for that field from view source of that page we can get same result.

                  1 .  Right click on page,click on View source.
                  2.   Get the java script id for that field in view source.
       
 Copy that id for the field country and use that id in URL as follows
 https://ap1.salesforce.com/a01/e?retURL=%2Fa01%2Fo&Name=FLEXANDSALESFORCE&00N90000002IoEJ=INDIA
     
Then u can see,

In this way you can fill data into all fields for an object using this URL trick.

Tuesday 7 June 2011

Displaying fields of multiple objects on Vfpage and inserting data into objects

Friends, Today i have explored on wrapper class, i have one scenario that is ,i want to display fields from multiple objects on vfpage and inserting data into objects at a time.For this requirement i have explored for that finally i came to know that we can handle it using wrapper class. My first experience with wrapper class is superb,i got solution for my requirement. I am sharing my code i hope it will helpful for you.
        I have two objects Students, Lineitems
                Student object having fields  Name,StuNumber__c
                Lineitems  object having fields Name,lineItemNumber__c
Now my requirement is show fields from both objects on vfpage and inserting data into them.
for that i have designed wrapper class .

       public class wrapperclass
         {
             public student__c Std{get;set;}
           
             public lineItem__c litem{get;set;}
           
             public wrapperclass(Student__c Std,lineItem__c lit)
             {
                 this.std = Std;
                 this.litem = lit;
             }
         }

first we need to define objects in wrapper class as shown above.We can  add more number of objects also.
To access those fields on Vfpage ,we need to declare as follows,


 <apex:repeat value="{!lstobjfields}" var="item" rendered="{!IF(lstobjfields.size > 0 , true , false)}" >
           <apex:pageBlockSection >
               <apex:inputField value="{!item.Std.Name}"/>
               <apex:inputField value="{!item.Std.stunumber__c}"/>
               <apex:inputField value="{!item.litem.Name}"/>
               <apex:inputField value="{!item.litem.Lineitemnumber__c}"/>
           </apex:pageBlockSection>
       </apex:repeat>


 I am giving complete code , u can understand by comments,

Page:-
<apex:page controller="addTextrBox" tabStyle="student__c">
  <apex:Form >
      <apex:pageBlock >
       <apex:commandButton Value="Add" action="{!addfields}"/>
       <br></br>
        <apex:repeat value="{!lstobjfields}" var="item" rendered="{!IF(lstobjfields.size > 0 , true , false)}" >
           <apex:pageBlockSection >
               <apex:inputField value="{!item.Std.Name}"/>
               <apex:inputField value="{!item.Std.stunumber__c}"/>
               <apex:inputField value="{!item.litem.Name}"/>
               <apex:inputField value="{!item.litem.Lineitemnumber__c}"/>
           </apex:pageBlockSection>
       </apex:repeat>
        <apex:commandButton Value="save" action="{!saveText}"/>
       </apex:pageBlock>
   </apex:Form>
</apex:page>

Controller:-

public class addTextrBox
{
    public List<wrapperclass> lstobjfields
        {
          get;
          set;
        }  
    public addTextrBox ()
        {
            lstobjfields = new List<wrapperclass>();
        } 
    public PageReference addfields()
        {
            try
                {
                    lstobjfields.add(new wrapperclass(new Student__c(),new lineItem__c()));   // Adding fields toVfpage when user click on Add Button.
                }
            catch(Exception e)
                {
                    ApexPages.addMessages(e);
                }
            return ApexPages.currentPage();
        }
     public class wrapperclass   // wrapper class to handle multiple objects.
         {
             public student__c Std{get;set;}
             public lineItem__c litem{get;set;}
             public wrapperclass(Student__c Std,lineItem__c lit)
             {
                 this.std = Std;
                 this.litem = lit;
             }
         }
      public PageReference saveText() // this method for inserting records into multiple objects.
        {
            try
                {
                    List<student__c> listStudent = new List<student__c>();
                    List<lineItem__c> lineItem = new List<lineItem__c>();
                   for(wrapperclass item : lstobjfields)
                    {
                            listStudent.add(item.Std);
                            lineItem.add(item.litem);  
                    }
                      if(listStudent.size() >  0 && lineItem.size() > 0)
                        insert lineItem;    // Inserting records in to multiple objects
                        insert listStudent;         
                }
            catch(Exception e)
                {
                    ApexPages.addMessages(e);
                }
            return ApexPages.currentPage();
        }
}







I hope this will be useful for u.

          
    

Welcome message for user when user loges into salesforce.

When i was exploring on home page components, i got an idea to show Welcome for user.For that i have write a small piece of code.
                We can create 3 types of homepage components
                                       Links
                                       Images
                                       Html Area.
 Where we can add Links and Images in Narrow space of homepage , html area is added to wide area of homepage . In Html Area we can write our custom Html code and we can display them in home page.
where i got an idea to show an popup/alert for user when ever he loges to salesforce.
I will explain you insteps please follow step by step


              1 .  Select Html Area component(Setup-->Appsetup-->Customize-->Home-->Home page components)
              2.  There you can find an check box " Show Html",Please select that and copy the following  code and save it as  "Homepagealert".
             
                <script>window.onload=get;
                      function get()
                      { 
                          alert('hai Hari');
                          url='/apex/user' ;
                          newwindow=window.open(url,'name','height=300,width=250');
                      }
                 </script>
              <h1>Flex And Salesforce Blog by Hari </h1>
In the above example i am showing an alert message and Vfpage as Popup.
Please find the Vfpage code:


     <apex:page wizard="true" >
             <Center><H2> Hello</H2><h1>{!$User.FirstName}</h1></center>
           <Center><B> Congratulations! You Have Successfully logged into Your Account</B</Center>
      </apex:page>


Save it. 
     Now goto Home-->Homepagelayout-->Click on Edit.
     Now you can find "Homepagealert"  in wide area section and select that and click on save. Now once logged out and logged in  to salesforce account click on home tab,you can find an alert/popup.