Saturday, 28 March 2015

How to Add rows in a visualforce page ?

Hi guys,

Last month I got an opportunity to work on very much exploited functionality :P ::P i.e Adding rows in visual force page. Although, you ll find numerous of example on Google.

There are many simple examples on internet.

Scenario:- On a visual force page , whenever the page loads it should have five rows a default of contact fields. Also i should have a button of adding rows i.e 5 on click of that button .

Lemme share you the result first (See the screen shot below)



Solution:-  Let me add the code and ll explain you section wise. Lets start with visual force page first.

<apex:page StandardController="Contact" extensions="CreateContctss">
    <apex:form >
    <!--<apex:pageMessage strength="3"  />-->
    
    <apex:outputPanel id="OutMessage">
           <apex:pageMessages rendered="{!errorMessage}"/> 
    </apex:outputPanel> 
    <apex:outputPanel id="addrows">
        <apex:pageBlock >

          <table>
            <tr>
                <td>First Name</td>
                <td>Last Name</td>
                <td>Email</td>
            </tr>
                <apex:repeat value="{!contactList}" var="con">
             <tr>
                    <td><apex:inputtext value="{!con.wrapperContact.Firstname}" id="idOFFirstname"/></td>
                    <td><apex:inputtext value="{!con.wrapperContact.LastName}" id="theValue"/></td>                    
                    <td><apex:inputtext value="{!con.wrapperContact.email}" id="idOFEmail"/></td>
                </tr>
            </apex:repeat>
        </table>
                <apex:pageblockButtons >
                    <apex:commandButton value="Add Contact" action="{!redirectPage}" />
                    <apex:commandButton value="Add rows" action="{!AddRows}" reRender="addrows"/>

                </apex:pageblockButtons>
        </apex:pageBlock>
      </apex:outputPanel>  
    </apex:form>
</apex:page>


So, we have to use the apex:repeat tag. To Iterate over the wrappercontact list . So that it should repeat the list 5 times whenever the page is loaded.
We have a button Add rows which adds five more similar rows on button pressed.

i am using the standard controller i. Contact and its extension for enhancing its functionality.

So, lets jump to code .

public with sharing class CreateContctss {
   public list<wrapperContact> wrapperContList{get; set;}
   public boolean errorMessage{get;set;}
   public boolean recordInserted{get;set;}
   
   Id acoountID = apexpages.currentpage().getparameters().get('IdOfAccount');
   Id newId= apexpages.currentpage().getparameters().get('newid');
   
   public list<Contact> listOfwrappedContact = new list<Contact>();
   
   //public List<wrapperContact> wrapperContList= new List<wrapperContact>();
   public list<wrapperContact> contactList{ get{
            if(wrapperContList == null){
               system.debug('wrapperContlist=='+wrapperContList);
               wrapperContList = new list<wrapperContact>();
               system.debug('wrapperContlist=='+wrapperContList);
                System.debug('hello.....'+wrapperContList);        
                for(integer i= 1; i<6; i++){
                    if(newId == null){
                        wrapperContList.add(new wrapperContact(new contact(AccountID = acoountID)));
                        System.debug('newId =='+newId);
                        system.debug('wrapperContlist=='+wrapperContList);
                        }else{
                        System.debug('newId =='+newId);
                        system.debug('wrapperContlist=='+wrapperContList);
                            wrapperContList.add(new wrapperContact(new contact(AccountID = newId)));
                        }
                    }
                }
                return wrapperContList ;
                }
                set;}
      
   /* public list<Contact> contactList {get{
            if(contactList == null){
                contactList = new list<Contact>();
                System.debug('hello.....'+Contactlist);        
                for(integer i= 1; i<6; i++){
                    if(newId == null){
                    contactList.add(new Contact(AccountID = acoountID ));
                    System.debug('newId =='+newId);
                        }else{
                        System.debug('newId =='+newId);
                            contactList.add(new Contact(AccountID = newId));
                        }
                    }
                }
                return contactlist;
                }
                set;}*/
    public CreateContctss(ApexPages.StandardController controller) {
        errorMessage = false;
        recordInserted= false;
        ///wrapperContList= null;
    }

    
    private void insertContact(){
        listOfwrappedContact.clear();// which is better approach 
        for(wrapperContact con : wrapperContList){
            listOfwrappedContact.add(con.wrapperContact);
        }
        string error;  
        system.debug('wrapperContlist=='+wrapperContList);
        Database.SaveResult[] srList = Database.insert(listOfwrappedContact , false); // used database.save result because if there are more required fields in future then it would be easier for us to handle 
           System.debug(srList);
           for (Database.SaveResult sr : srList) {
                if (sr.isSuccess()) {
                    // Operation was successful, so get the ID of the record that was processed
                    System.debug('Successfully inserted account. Account ID: ' + sr.getId());
                    recordInserted= true;
                }
                else {
                // Operation failed, so get all errors                
                for(Database.Error err : sr.getErrors()) {
                    System.debug('The following error has occurred.');                    
                    System.debug(err.getStatusCode() + ': ' + err.getMessage());
                    System.debug('Account fields that affected this error: ' + err.getFields());
                    error = + err.getMessage();
                    errorMessage = true;
                    }
                }
           }
               /* ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please fill at least one Last name ');
                ApexPages.addMessage(myMsg);*/
       }    
    public PageReference redirectPage(){
    try{
     insertContact();
     }catch(exception e){
                 ApexPages.AddMessages(e);
                 return null;
     }
     for(wrapperContact con : wrapperContList){
         system.debug('LastName1'+con.wrapperContact.LastName);
         system.debug('Email1'+con.wrapperContact.Email);
         Boolean result;
         Boolean emailerror;
         Boolean LastNameerror;
         if(con.wrapperContact.Email != ''){
            String emailRegEx = '[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\*\\/\\=\\?\\^\\_\\+\\-\\`\\{\\|\\}\\~\'._%+-]+@[a-zA-Z0-9\\-.-]+\\.[a-zA-Z]+';
            Pattern MyPattern = Pattern.compile(emailRegex);
            Matcher MyMatcher = MyPattern.matcher(con.wrapperContact.email);
            result = MyMatcher.matches();
            System.debug('Result'+result);
            }
        
         if(result == false){
              ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please check email format');
              ApexPages.addMessage(myMsg);
             emailerror = true;
         }
         System.debug(con.wrapperContact.lastname.length());
         if(con.wrapperContact.lastname.length() > 80){
         system.debug('more than 80');
              ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Last name cannot be too large ');
              ApexPages.addMessage(myMsg);         
              //return null;
              }
              
         if(con.wrapperContact.lastName == ''){
            if( recordInserted == false){   
         
          System.debug(con.wrapperContact.lastName);
          ApexPages.Message myMsg = new ApexPages.Message(ApexPages.Severity.FATAL,'Please fill at least one Last name ');
          ApexPages.addMessage(myMsg);
          LastNameerror= true;
              
                }
         }
         if(LastNameerror== true || emailerror == true){return null;}
     }
     if(newId == null){
         pagereference prt= new pagereference('/'+acoountID).setRedirect(true);
         return prt;
    }else{
        pagereference prr= new pagereference('/'+newid).setRedirect(true);
        return prr;
        }  
    }

            Public pagereference  addRows(){
                //wrapperContList = new list<wrapperContact>();
                for(Integer i=0;i<5;i++){
                  if(newId == null){
                    wrapperContList.add(new wrapperContact(new contact(AccountID = acoountID)));
                    System.debug('newId =='+newId);
                    system.debug('wrapperContlist=='+wrapperContList);
                        }else{
                            System.debug('newId =='+newId);
                            system.debug('wrapperContlist=='+wrapperContList);
                            wrapperContList.add(new wrapperContact(new contact(AccountID = newId)));
                        }
                    }
            return null;
        }
    
    public class wrapperContact{
        public Contact wrapperContact{get;set;}
        public wrapperContact(contact c){
            wrapperContact = c;
        }
    }
}

I have to use wrapper class to contain it as one entity. Because every time I click on Add rows button I need to do some process as a whole.

ignore apex.pages.currentpage().get('id') as of now.

Your focus area should be only Add rows method . In this, we have to iterate over the wrappercontlist. and add them to visual force page.

Important point to note here is rendering . You need to use output panel id . to reRender on page .

Keep Learning Salesforce

Thanks
Cheers
ankushsalesforce@gmail.com



No comments:

Post a Comment

oAuth Use Case -  Headless API Explained in the Easiest way Wondering why? and When we use the Headless API flow Use case example: Imagine a...