Sunday, 16 July 2017

Not rendering Clickable Link on Visualforce Page in apex:pageMessages

Hi Folks,

I was trying to cover a scenario I need to show a clickable link on visualforce page on some error condition with a navigating back to original record. 

I know we have in built standard tag i.e 

apex:pageMessages


Lets say you want to show a clickable message that needs to be redirected to some other link . This navigation can be done within or outside salesforce. So, generally we use the below line to show the clickable link. 

           String orderId = System.URL.getSalesforceBaseUrl().toExternalForm();
            String err = '<b><a href="' + orderId +'/'+OrderId+ '">Click Here to Continue  here</a>.';
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,err));

But some how it was showing me on the page as like this "'<b><a href="' + orderId +'/'+OrderId+ '">Click Here to Continue here"

But then I checked that there is an attribute i.e Escape

A Boolean value that specifies whether sensitive HTML and XML characters should be escaped in the HTML output generated by this component. If you do not specify escape="false", the character escape sequence displays as written. Be aware that setting this value to "false" may be a security risk because it allows arbitrary content, including JavaScript, that could be used in a malicious manner.

If I make Esacape = false then it renders as link. 

Thanks
Ankush


Happy Coding 😉




Friday, 31 March 2017

Updates From Spring 17 Release Notes -Key Points to Remember

Hi Folks,

It's very much hot outside , as summers are already up. I was notified for my maintenance exam and thought to go through the release notes of Spring' 17.

Salesforce is ramping up pretty fast with all its new features and products. As a developer need to catch up with all the updates.

Thought to share the updates with all of you.

Here are the few key points that may help you for Spring Release:-

  1.  Global Action Menu :- 

    Global Actions are another awesome feature that has some updates like its capabilities to :-
    • Take notes
    • Launch Visualforce
    • Create records          
     2.   Favorites in Lightning Experience:-
    • Only User Can edit his or Favourites.
     3. If an old post with a file is shared in Lightning Experience, Then how is the new file in the          newly shared post will look like. 
 
    • A link to the file is shared and it is available as a link.
     4. Merged in Lightning Experience:-

    • Only 3 Records can be merged at once.
     5.  Predefined values for send email action:-

    • TO
    • CC
    • BCC
      6.  Lightning Record Pages can be assigned to:-
    • Record types
    • Apps
    • Profiles
       7. Three types of content can shortcuts be created for using Favorites:-

    •  Dashboards
    • Record home pages
    • Chatter groups
        8.   Feature that enables creating, updating and deleting records in other Salesforce orgs:-

    • Salesforce Connect Cross-Org Adapter.
       9.  An image included in the Salesforce Lightning Design System from a Visualforce page ,                Mark ups for the same :-
    • <apex:slds>
    • $Asset
      10.  Capabilities Of Global Actions Menu:-


  • Launch a custom Visualforce Page.
      • Launch a custom Canvas App.
      • Launch a custom Lightning Component.
            11.  Detailed information about the status of an Apex batch job:- 

      • Elapsed time
      • Submitted date
            12.  component type will display the details of the parent Account from a custom Lightning                       record page for the Contact object  :-


      • Related record component









    Thursday, 26 January 2017

    Simple Pagination In salesforce

    Hi Folks,

    Its been long since I have written any blog. Please welcome me :P.

    Ok. lets roll to business. I ll be sharing simple way of Pagination in salesforce. Lemme first Explain you the three variable I have used here in my Apex class :-

    totalRecs = 0;
    OffsetSize = 0;
    LimitSize= 10;

    totalRecs is used for tracking the total number of records that have fetched. So that I can deduct it fro the total number of records that have been shon so far in previous pages.

    OffsetSize is used for showing the rest of the records on the current page number.

    Limitsize is used for declaring the count of records that will be shown on every page.

    So guys dnt worry here is the code:-



    
           public class Pagination
    {
            private integer totalRecs = 0;
            private integer OffsetSize = 0;
            private integer LimitSize= 10;
            public Pagination()
            {
                totalRecs = [select count() from account];
            }
            public List<account> getacclist()
            {
                List<account> acc = Database.Query('SELECT Name, website, AnnualRevenue, description, Type FROM account LIMIT :LimitSize OFFSET :OffsetSize');
                System.debug('Values are ' + acc);
                return acc;
            }
            public void FirstPage()
            {
                OffsetSize = 0;
            }
            public void previous()
            {
                OffsetSize = OffsetSize - LimitSize;
            }public void next()
            {
                OffsetSize = OffsetSize + LimitSize;
            
            }
            public void LastPage()
            {
                OffsetSize = totalrecs - math.mod(totalRecs,LimitSize);
            }
            public boolean getprev()
            {
            if(OffsetSize == 0)
                return true;
                else
                return false;
            }
            public boolean getnxt()
            {
                if((OffsetSize + LimitSize) > totalRecs)
                return true;
                else
                    return false;
            }
    }



    
           <apex:page controller="Pagination" sidebar="false" showHeader="false">
    <apex:form >
        <apex:pageBlock id="details">
            <apex:pageblockTable value="{!acclist}" var="acc">
                <apex:column value="{!acc.Name}"/>
                <apex:column value="{!acc.website}"/>
                <apex:column value="{!acc.AnnualRevenue}"/>
                <apex:column value="{!acc.Description}"/>
                <apex:column value="{!acc.Type}"/>
        </apex:pageblockTable>
    <apex:pageblockButtons >
        <apex:commandButton value="First Page" rerender="details" action="{!FirstPage}" disabled="{!prev}"/>
        <apex:commandButton value="Previous" rerender="details" action="{!previous}" disabled="{!prev}"/>
        <apex:commandButton value="Next" rerender="details" action="{!next}" disabled="{!nxt}"/>
        <apex:commandButton value="Last Page" rerender="details" action="{!LastPage}" disabled="{!nxt}"/>
    </apex:pageblockButtons>
    </apex:pageBlock>
    </apex:form></apex:page>



    Thanks
    Happy Coding !!

    Cheers!!

    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


    My AI Channel

    Hi Folks,  Its been a while posted any post on Salesforce. I feel like Salesforce can waith but new AI hype cant, need to go with the flow. ...