Sunday 1 November 2015

Blank Values in Merge Fields HTML template sending mail through Apex code Salesforce!

Hi Folks,

Its been ages since am here. I switched to a new company got busy there. Anyways,,, Lets get started with another requirement and isssue.


Issue:- I was unable to get values in merge fields from the template that I have qurried. 






       
So if we want to use standard email template then we have to use setWhatId to specify the record for which the merge fields should calculate . But the limlitation here is if we have setTargetObjectId which should be Id of  user , contact or a lead. This will not work if we user Id as a setTargetObject Id. It needs to be a contact Id . Otherwise, email which you will receive will have blank value. 

Cheers
Ankush







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


Wednesday 18 February 2015

How to overide standard salesforce save button?

Hi guys!

Yesterday, I was working on overiding the standard save and cancel button. I know there are many blogs you ll find easily on google.

Anyways, am just sharing just to add a simple way(I think , u may find more easier  :P:P) of overiding . Lets jump to scenario.

Scenario:-  Say, I have a custom visualforce page abc and from there I have given a button on that page. When that button is pressed, it should take us to standard edit page of account. After clicking the save button it should take us to custom visualforce page. lets say to xyz page.



So , you guys are aware of  URL parameters that are appended when you open standard detail page of account inedit mode it is like :-

https://na15.salesforce.com/001/e?retURL=%2F001%2Fo

So, what happen is after you fill the details. and hit save button. it takes you to the record itself . It is the standard salesforce  functionality.

Lets see what these parameters are meant for:-

1. 001 - it is id of account object.
2. 001/e?-  It stands for edit mode .
3. retURL - It is the url when you click the cancel button
4. saveURL - It is the URL for landing page.

So, my requirement is that I have to redirect from my custom visulforce page to account edit page.
to do this - in your page refrnce method append this

pagereference pr= new pagereference('/001/e?retURL=/apex/AccountSearch&saveURL=/apex/CreateContac').setRedirect(true);

Thanks
Ankush






Sunday 1 February 2015

How salesforce matches Contact to the case when an email is received in Email-To-Case

Hi Guys,

I have been working on salesforce's Email to case Functionality since December. I cant say am perfect in it , but have got a good hold as of now.

Let me just walk you through how salesforce Email-To-Case functionality works. Though , ll not brief here about setting email to case .

So, when an customer sends an email to salesforce org. Then a case is created in the salesforce.

Let say, You have a contact  with a name xyz and his email address is xyz@abc.com. So, when he ll send an email to raise a case, his case will be created and and his contact will be asscoiciatd  with this case.

And how salesforce does this, all explationaltion is given here in salesforce know;ledge article.

CLICK HERE.


Thursday 15 January 2015

Trigger on Parent Object to copy the fields on its child record in Salesforce!!

Hi Guys!!

Its been long time since I have been here. My obsession with salesforce has taken next level.

Still, I love writing triggers. I know all these are very small triggers. But it may help beginners who are trying to connect to salesforce.

Anyways, lets start with another trigger(Only for beginners) .

Scenario:-

I have to replicate a field of parent object to all its child records. It is very simple scenario for experience people.

Here is the code for you folks....

Trigger replicateFieldsOnChild on Parent (After update){
 Set<id> setOfParentId = new Set<Id>();
 for(Parent pt : trigger.new){
  setOfParentId.add(pt.id);
 }
 List<Child> listChild = new List<Child>([Select id, parentId from child where ParentId in: setOfParentId]);
 List<Child> updatedlistChild = new List<Child>
 for(Parent pt : trigger.new){
  for(Child ch : listChild){
   ch.field = pt.field;
   updatedlistChild.add(ch);
  }
 }
 Update updatedlistChild;
}


Remember :-  There are may ways of doing a job . You may find more simpler and efficient way. keep Exloring!


Happy coding 

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