Showing posts with label Salesforce. Show all posts
Showing posts with label Salesforce. Show all posts

Thursday, 28 July 2016

Using Salesforce standard modal in a Detail page button


Javascript button to open an iframe using Salesforce standard modal.


Create a detail page button, set it to javascript and add the following code:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
(function() {
    var box = new SimpleDialog("spoon" + Math.random(), true);
    box.setTitle("Dialog title");
    box.displayX = true;
    box.isMovable = false;
    box.createDialog();
    box.setWidth(750);
    box.setContentInnerHTML(
        "<iframe src='REPLACE WITH YOUR URL' frameborder='0' width='100%' height='380px' />"
    );
    //set the height of the modal
    box.dialog.children[1].style.height = '400px';
    box.show();
    //if displayX is true, then override standard close event by this code
    box.dialog.getElementsByClassName('dialogClose')[0].onclick = function() {
        box.hide();
    };
    //optional : add this to close the modal onclick of the overlay background
    box.background.addEventListener('click', function() {
        box.hide();
    });
})();

Output:

Sunday, 24 May 2015

DataTables in Visualforce Part 1

Introduction

One day a client asked us to display the Opportunities of an Account. We thought a nice Visualforce PageBlockTable would do the job. Then the client added functionalities like:

  • Pagination (as there would be around 100 records),
  • Sorting of columns,
  • Filtering of opportunities.
Instead of scratching our head thinking how to do this in Visualforce, we laughed out loud and told the client that the solution will be available in 5 minutes :)

DataTables our Saviour

DataTables is a jQuery plugin which we will use to make the dream of our client come true. DataTables focuses on enhancing the user-experience on standard HTML tables.

Code

Below is a small code used to generate our table of Opportunities. Notice how we import our scripts and css for DataTables; you should normally put them in a Static Resource. At line 15, we called the dataTable function to initialise our table.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
<apex:page standardController="Account">
    <apex:includescript value="//code.jquery.com/jquery-1.11.1.min.js" / >
    <apex:includescript value="//cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js" />
    <apex:stylesheet value="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css" />
    
    <apex:dataTable value="{!Account.Opportunities}" var="opp" styleClass="opp-table">
        <apex:column value="{!opp.Name}" headerValue="Name"/>
        <apex:column value="{!opp.StageName}" headerValue="Stage"/>
        <apex:column value="{!opp.Amount}" headerValue="Amount"/>
        <apex:column value="{!opp.CloseDate}" headerValue="Close Date"/>
    </apex:dataTable>
    
    <script>
        $(function(){
            $('table.opp-table').dataTable();
        });
    </script>
</apex:page>

Result



  1. Pagination controls
  2. Pagination size controls
  3. Sorting by clicking on column header. (currently sorted on Amount)
  4. Instant filtering capability over whole table.
Final words

This is a basic example of using DataTables in Visualforce. Part 2 coming soon...


Cheers & Happy Coding !!
Gulshan.

Thursday, 16 October 2014

Apex Map into JSON for use in Javascript / jQuery

Introduction

Ever wondered how to use your apex map into javascript / jQuery for your VisualForce development?
Please find below a way to do it.

Note: jQuery is required in this tutorial.

Apex Class (Visualforce Controller)

Suppose we populate a map with key Id and value as a list of Ids, say mapParentIdListChildrenId in our controller.
We then declare a getter to access this map as JSON in our VF page.
 public Map <Id, List <Id>> mapParentIdListChildrenId{get;set;}
 public String mapParentChildrenJSON {get{return JSON.serialize(mapParentIdListChildrenId);}}
Visualforce Page

The JSON String mapParentChildrenJSON is converted into javascript object as shown below:
 <script> 
  $(function() {
     var $mapParentChildren = jQuery.parseJSON('{!JSENCODE(mapParentChildrenJSON)}');
     console.log($mapParentChildren);
     // var value = $mapParentChildren[key]; // can be used to access values of the map
  }
 </script>
Use the Console of your browser to inspect the elements in your map ;)

Cheers & Happy Coding !!
Gulshan.

Thursday, 15 May 2014

Padding Text in Salesforce / Visualforce

Introduction

Last time I got a request from a client to limit a number to 6 digits and if the number has less than 6 digits, prepend 0 in front of it.

Example: 7007 must become 007007

I had to do this in 
  1. Javascript (for display in a disabled textbox) , 
  2. Visualforce (for display in a PDF), and 
  3. Apex (to send to a Web Service).

Javascript

For the Javascript version, I wrote a small function that would do the left padding of zeroes. This function is called when the page is loaded.
 function addZeroes(eId, size){  
      var elem = document.getElementById(eId)  
      while(elem.value.length < size)  
           elem.value = "0" + elem.value  
 }

The function takes the element Id and size as parameter to limit left padding. In my case the element was an input of type text:
 <input id="agent_number" type="text" value="{!$User.Agent__c}" disabled="true"/>  

The addZeroes() function was called as follows in a <script> tag after the form was loaded.
 <script>  
      addZeroes("agent_number", 6);  
 </script>  

Visualforce

The visualforce solution was hard to find but very simple to implement. I used the formula LPAD.
 {!LPAD($User.Agent_No__c,6,'0')}  

Apex

I could not find a solution that resembles the visualforce LPAD in Apex. I used two methods from the String Class to achieve the same result.
 String agentNum = '7007';  
 String agentNumber = agentNum.leftPad(6).replace(' ', '0');  
 system.debug('## agentNumber : ' + agentNumber);  
leftPad() method is used to pad spaces in front without exceeding the length parameter.
replace() method is used to replace all the spaces with 0.

Thnx & Cheers,
Gulshan.

Sunday, 4 May 2014

Twitter Application-only authentication in Salesforce Apex

Hello all,

Today I will be posting an example on how to implement the Twitter Application-only authentication using Salesforce Apex.

Overview


The Twitter Application-only authentication is used when no user sign-in with Twitter is required.
When using this type of authentication, we are allowed to call limited Twitter functionalities, namely :


  • Pull user timelines;
  • Access friends and followers of any account;
  • Access lists resources;
  • Search in tweets;
  • Retrieve any user information;

  • In our example, we will be implementing the Authentication flow described in Twitter Application-only authentication which involves two HTTP requests.

    Code


     public TwitterContr(){  
          HttpRequest req = new HttpRequest();  
          req.setMethod('POST');  
          req.setEndpoint('https://api.twitter.com/oauth2/token');  
            
          //// Step 1: Encode consumer key and secret  
            
          String consumerKey = 'xvz1evFS4wEEPTGEFPHBog';  
          String consumerSecret = 'L8qq9PZyRg6ieKGEKhZolGC0vJWLw8iEJ88DRdyOg';  
            
          Blob headerValue = Blob.valueOf(consumerKey + ':' + consumerSecret);  
          String authorizationHeader = 'Basic ' + EncodingUtil.base64Encode(headerValue);  
         
          //// Step 2: Obtain a bearer token  
                 
          req.setHeader('Authorization', authorizationHeader);  
          req.setHeader('Content-Type','application/x-www-form-urlencoded;charset=UTF-8');  
          req.setBody('grant_type=client_credentials');  
         
          // Create a new http object to send the request object  
          // A response object is generated as a result of the request  
          // the server will respond with a JSON-encoded payload  
         
          Http http = new Http();  
          HTTPResponse res = http.send(req);  
          
          String jsonStr = res.getbody();  
          JSONParser parser = JSON.createParser(jsonStr);  
            
          // extract access token from JSON response  
          string accessToken;  
          while (parser.nextToken() != null) {  
               if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && (parser.getText() == 'access_token')) {  
                    // Get the value.  
                    parser.nextToken();  
                    accessToken = parser.getText();  
               }  
          }  
         
          // access token can now be used to perform other requests  
          //// Step 3: Authenticate API requests with the bearer/access token  
            
          // e.g. searching for tweets   
            
          HttpRequest req1 = new HttpRequest();  
          req1.setMethod('GET');  
          req1.setEndpoint('https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames');  
         
          String authorizationHeader1 = 'Bearer ' + accessToken;  
          req1.setHeader('Authorization', authorizationHeader1);  
         
          Http http1 = new Http();  
          HTTPResponse searchResponse = http.send(req1);  
          system.debug('## body1 : ' + searchResponse.getBody());  
     }  
    

    Cheers!!

    Saturday, 16 November 2013

    Insufficient Privileges

    Insufficient Privileges
    You do not have the level of access necessary to perform the operation you requested. Please contact the owner of the record or your administrator if access is necessary.

    Ever got the error above!!

    Even if you are an administrator!!

    Check that all your components (Apex Classes, Visualforce pages, Visualforce components,...) are using the same API version.

    Cheers!!

    Wednesday, 13 November 2013

    Some example usage of apex:param

     Here are some example usage of the apex:param tag in visualforce page :



    <apex:outputText value="{0,date,dd/MM/yyyy}">
            <apex:param value="{!E.Date_du_collecte__c}"/>
        </apex:outputText>
        //convert a decimal to integer in VF
        <apex:outputText value="{0,number,integer}">
            <apex:param value="{!d.key.Degustateur__r.PonderationNiveauTechnique__pc}"/>
        </apex:outputText>
        //replace . by ,
        <apex:outputText value="{0}">
            <apex:param value="{!SUBSTITUTE(TEXT(r.header.InvoiceAmount__c), '.', ',' )}"/>
        </apex:outputText>

        <apex:commandButton value="Process Nickname" action="{!processButtonClick}">
           <apex:param name="nickName" value="{!contact.firstname}" assignTo="{!nickName}"/>
        </apex:commandButton>
       
        <apex:commandButton action="{!DisplayAcompteJournal}" rendered="{!show.showSaveLines}" rerender="head02" value="Afficher Acompte">
            <apex:param name="pos" value="{!numCompteGeneralLine}" assignTo="{!linePosition}" />
        </apex:commandButton>

    Dynamic Apex: Get Field Type

    Dynamic Apex allows users to access the metadata information about sObject and fields.
    The requirement was to get the field type of a sObject.

    Schema.DescribeFieldResult f = Schema.sObjectType.Account.fields.Name;

    system.debug('## Field Type: '+f.getSObjectField().getDescribe().getType());
    //Returns: ## Field Type: STRING

    Example of other available methods that can be accessed from f.getSObjectField().getDescribe()
    • getByteLength=765;
    • getCalculatedFormula=null;
    • getController=null;
    • getDefaultValue=null;
    • getDefaultValueFormula=null;
    • getDigits=0;
    • getInlineHelpText=null;
    • getLabel=Account Name;
    • getLength=255;
    • getLocalName=Name;
    • getName=Name;
    • getPrecision=0;
    • getRelationshipName=null;
    • getRelationshipOrder=null;
    • getScale=0;
    • getSoapType=STRING;
    • getSobjectField=Name;
    • getType=STRING;
    • isAccessible=true;
    • isAutoNumber=false;
    • isCalculated=false;
    • isCascadeDelete=false;
    • isCaseSensitive=false;
    • isCreateable=true;
    • isCustom=false;
    • isDefaultedOnCreate=false;
    • isDependentPicklist=false;
    • isDeprecatedAndHidden=false;
    • isDisplayLocationInDecimal=false;
    • isExternalId=false;
    • isFilterable=true;
    • isGroupable=true;
    • isHtmlFormatted=false;
    • isIdLookup=false;
    • isNameField=true;
    • isNamePointing=false;
    • isNillable=true;
    • isPermissionable=false;
    • isRestrictedDelete=false;
    • isSortable=true;
    • isUnique=false;
    • isUpdateable=true;
    • isWriteRequiresMasterRead=false;

    Refer to salesforce documentation for further information