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



Saturday 14 March 2015

How To Deactivate the trigger in Production Org without modifying it?

Hi Guys,

I have a requirement that I need to deactivate a trigger without modifying it in production. Is there any magic wand to do this. Kidding, isn't. it :P

Obviously this is not my Idea , a friend of my told me how to do this so thought to share with all of you.

Solution:- 

Have your ever heard of custom setting. yes, In custom setting you need to make a check box field. name it switch.

Then in your trigger you need to querry the this custom  setting field and just check whether it is true or false. If it is true then run your logic otherwise do nothing.

Lemme  share the code snippet with you.

Trigger SwitchTrigger on Account (<event>){
if(Switch__c == true){
Your   *** Logic
}
}

So , when ever you want to deactivate the trigger in production just go to custom setting and uncheck the check box.


keep learning Salesforce
thanks
ankushsalesforce@gmail.com


Sunday 1 March 2015

how to use param tag in visualforce?

Hi guys,

Few days back , I was working on apex param tag. I had an requirement to insert a contact under the account I have clicked from different page. I don't have to provide the definition. to this as you know it is there on the internet .

Scenario: -  I have a custom page where I have the table which displays the account as command link. On clicking  any of the record of account should take me to a custom page where I can create contact. Contact which gets inserted should get associated to the account I clicked on.

Solution:-  We have to use the apex param tag in our page and have to send the ID to the url, when redirecting to to our custom contact page.

Lemme walk you through the code snippet:-

<apex:pageBlockTable value="{!Accounts}" var="item">
                           <apex:column headervalue="Account Name">
                                <apex:commandLink action="{!redirectPage}">
                                      <apex:param name="IdOfAccount" value="{!item.id}"/>
                                      {!item.Name}
                                </apex:commandLink>
                           </apex:column>
  </apex:pageBlockTable>

As you can see in the command link tag  have used apex param. In the param tag I have used name attribute and i have assigned it a name as 'IdOFAccount' , through this am sending the Id of account. which I have selected.

Lemme show How I am catching this parameter in code and redirecting to custom contact page.


    public PageReference redirectPage(){
        ID = apexpages.currentpage().getparameters().get('IdOfAccount');
        pagereference pr= new pagereference('/apex/CreateContac?IdOfAccount='+ID).setRedirect(true);
        return pr;
    }

As in command link in action attribute I have mentioned redirectPage. In the instance of pageref I have redirected it to createContact page with IdOfaccount from my visualforce page.


This How You can easily make the use of   Apex param tag.

Soon, I ll be uploading a video of demo.

cheers!

#happyCoding
ankushsalesforce@gmail.com


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...