Tuesday, June 23, 2015

Salesforce Primitive Data Types(dataTypes allowed in apex)


1. Blob – This data type represents binary data stored as a single object.
Example: Blob b1 = Blob.valueof(‘idea’);

2. Boolean – This data type represents Value that can only be assigned true, false, or null.
Example: Boolean isvar = true;

3. Date – This data type represents particular day.
Example: Date myDateVar = Date.today();
Date weekStart = myDateVar.toStartofWeek();

4. Datetime – This data type represents particular time and date.
Example: Datetime myDateTimeVar = Datetime.now();
Datetime newd = myDateTimeVar. addMonths(5);

5. Decimal – This data type represents Number that includes a decimal
point. Decimal is an arbitrary precision number.
Example:Decimal myVar = 12.4567;
Decimal divDecVar = myVar.divide(7, 2, System.RoundingMode.UP);
system.assertEquals(divDecVar,1.78);

6. Double – Represents 64-bit number that includes a decimal point. Minimum value -2^63. Maximum value of 2^63-1.
Example:Double d=3.14159;

7. ID – Represents 18-character Force.com record identifier.
Example:ID id=’00300000003T2PGAA0′;

8. Integer – 32-bit number that doesn’t include a decimal point. Minimum value
-2,147,483,648 — maximum value of 2,147,483,647
Example: Integer i = 1;

9. Long – Represents 64-bit number that doesn’t include a decimal point. minimum value of -263 — maximum value of 263-1.
Example:Long l = 2147483648L;

10. String – Represents Set of characters surrounded by single quotes.
Example:String s1 = ‘Hello';

11. Time – Represents particular time.
Example: Time myTimeVar = Time.newInstance(18, 30, 2, 20);
Integer myMinutes = myTimeVar.
minute();

12. sObject - Salesforce object (Custom or Standard)
Example : List<sObject> obj = new List<sObject>();

Collections
-----------
1. List
2. Set
3. Map

Monday, June 8, 2015

AngularJS Filters Example with Salesforce Page (Bootstrap style)


Example Visualforce Page
<apex:page controller="ContactListView" sidebar="false" >
    
     <style>
         tr.dataRow {
           background-color:white;
         }
         tr.dataRow:hover {
           background-color: #e3f3ff;
         };
     </style>
     
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap-theme.min.css" />
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
     <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    
    <apex:pageBlock >
    
        <div ng-app="ContactListViewApp" ng-controller="ContactListViewController">
            <div class="row">
                <div class="form-group col-md-2">
                    <label> Search: </label>
                    <input type="text" ng-model="keyWord.$" placeholder="Enter keyword" />
                </div>
                <div class="form-group col-md-2">
                    <label> Contact Search: </label>
                    <input type="text" ng-model="keyWord.Name" placeholder="Enter Contact name" />
                </div>
                <div class="form-group col-md-2">
                    <label> Account Search: </label>
                    <input type="text" ng-model="keyWord.Account.Name" placeholder="Enter Account name" />
                </div>
                <div class="form-group col-md-2">
                    <label> Phone Search: </label>
                    <input type="text" ng-model="keyWord.Phone" placeholder="Enter Contact pnone"/>
                </div>
            </div>
            <div  style="height: 600px;overflow: auto;" class="table-responsive">
            
                <table cellpadding="0px" cellspacing="0px" class="table table-striped table-hover">
                    <tr>
                        <th> Name </th>
                        <th> Account </th>
                        <th> Phone </th>
                    </tr>
                    <tr ng-repeat="con in conListJSON | filter:keyWord">
                        <td>
                            {{ con.Name }}
                        </td>
                        <td>
                            {{ con.Account.Name }}
                        </td>
                        <td>
                            {{ con.Phone }}
                        </td>
                    </tr>
                </table>
            </div>
            <script>
                angular.module('ContactListViewApp', []).controller('ContactListViewController', function($scope){
                    
                    $scope.conListJSON = JSON.parse('{!conListJSON}');
                    console.log($scope.conListJSON);
                    console.log(JSON.stringify('{!conListJSON}'));
                });           
            </script>        
        </div>
    </apex:pageBlock>
</apex:page>


Example Controller

public class ContactListView {
    
    public List<Contact> conList{get;set;}
    public String conListJSON{get;set;}
    public ContactListView(){
    
        conList = [SELECT Id, Name, AccountId, Account.Name, Phone FROM Contact WHERE AccountId != NULL];      
        conListJSON = JSON.serialize(conList);  
        conListJSON = String.escapeSingleQuotes(conListJSON);
    }
}

Thursday, June 4, 2015

Salesforce HTML5 Manifest (Visualforce Offline Access)

Simple Example for Offline Manifest in Salesforce Visualforce.

- Salesforce cache supported version : upto 26

You can check the caches in "chrome://appcache-internals/"

Page1: TestPage1

<apex:page showHeader="false" standardStylesheets="false" contentType="text/cache-manifest">CACHE MANIFEST
#review
/apex/testpage2?cache=cache2

NETWORK:
*
</apex:page>


Page2 : TestPage2

<apex:page showHeader="false" sidebar="false" standardStylesheets="false" docType="html-5.0" manifest="/apex/TestPage1">

     <header>
          <h1>Congratulations!</h1>
    </header>
      <article>
         <p>This page looks almost like HTML5!</p>
     </article>

</apex:page>

Saturday, May 2, 2015

Multiplication calculator JQuery

<html>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <style>
        .schTable{}
        .noOfPay{}
        .amount{}
    </style>
    <body>
        <table class="schTable">
            <tr>
                <td> Total </td>
                <td id="totalId"> </td>
            </tr>
            <tr>
                <td>Input 1 </td>
                <td> Input 2 </td>
            </tr>
             <tr>
                <td><input type="text" class="noOfPay" onkeyup="calculateTotal();" /> </td>
                <td><input type="text" class="amount" onkeyup="calculateTotal();"/> </td>
            </tr>
             <tr>
                <td><input type="text" class="noOfPay" onkeyup="calculateTotal();"/> </td>
                <td><input type="text" class="amount" onkeyup="calculateTotal();"/> </td>
            </tr>
        </table>
    </body>
    <script>      
        var noOfPayArray = [];
        var amountArray = [];
        function calculateTotal(){  
            var i = 0;        
            $(".schTable .noOfPay").each(function( e ) {
               noOfPayArray[i] = $(this).val();
               i++;
            });
           
            i = 0;        
            $(".schTable .amount").each(function( e ) {                
                amountArray[i] = $(this).val();
                i++;
            });
            var total = 0.00;
            for(var i =0; i < amountArray.length; i++){              
               
                if(noOfPayArray[i] != '' && amountArray[i] != '' &&  noOfPayArray[i] != 'null' && amountArray[i] != 'null' && noOfPayArray[i] != null && amountArray[i] != null && !isNaN(noOfPayArray[i]) && !isNaN(amountArray[i])){
                 
                    total += parseFloat(noOfPayArray[i]) * parseFloat(amountArray[i]);
                }
            }
            document.getElementById('totalId').innerHTML = total.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");          
                   
        }      
    </script>
</html>

Tuesday, April 7, 2015

Web Chart's List


i) D3.js — Data-Driven Documents
    - Open source
    - https://github.com/mbostock/d3/wiki/Gallery

ii) Google Visualization Charts  
    - Pie chart doesn't show the connected lines for all slices
   
iii) Fusioncharts (http://www.fusioncharts.com/charts/pie-doughnut-charts/)
    - With "Fusionchart watermark" its free for both personal and commercial
    - If we need to remove water mark, we need to buy the licence
    - 2d Pie chart available with connected lines
   
iv) Flot
    - Flot is completely free to use and commercial support is provided on special request to the creator.
    - Pie chart available

v) ChartJs
    - Open source
    - Pie chart available
    - Not sure about connected legends

vi) EJS Chart
    - EJS Chart comes in free and paid versions. The free version limits you to use maximum of 1 chart per page and 2 series per chart.
   
vii) uvCharts
    - Open source
    - D3.js base
    - No connected lines for pie chart

viii) Chartist.js
    - Its animations only supported in modern browsers
    - No clear examples for pie charts
   
ix) jqChart - http://www.jqchart.com/jquery/chart/ChartTypes/PieChartLabels
    - Matched with requirement
    - Trail version only available for download
    - Licensed

x) amCharts (http://www.amcharts.com/demos/pie-chart-with-legend/)
    - The free version of amChart will leave a backlink to its website on the top of every chart.
    - Pie chart looks good
    - Commercial

xi) MeteorCharts
    - Commercial
   
xii) Highcharts JS
    - Free for personal use
    - Licence for commercial
    - Pie chart available

xiii) Chartkick
    - Its built for Ruby Application
    - Code available for Rubly only
   
xiv) n3-charts
    - Pie chart not available

xv) Ember Charts
    - Open source
    - Connected legend option not available
   
xvi) Smoothie Charts
    - Pie chart not available
    - Displaying only  smooth live time lines
   
Source : http://www.sitepoint.com/15-best-javascript-charting-libraries/

Sunday, April 5, 2015

Salesforce Userful Links - Part II

Salesforce1 App tutorial
http://ccoenraets.github.io/salesforce1-app-tutorial/object-action-create-record.html

Salesforce1 App Coding tutorial
http://ccoenraets.github.io/salesforce-developer-workshop/Using-JavaScript-in-Visualforce-Pages.html

SOURCE :http://www.eltoro.it/ArticleViewer

Salesforce1 Demo: Building an Expense Tracker
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000T3GOpIAN

Displaying Errors in VisualForce page, using yellow background box.
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRinIAH

Sending Emails From an Apex Trigger Using a VisualForce template.
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRitIAH

URLFOR() explained
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRjBIAX

Apex Collections
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000VOeg8IAD

Create Excel files with multiple tabs.
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRiIIAX

DML: Standalone Statements or Database Methods Which One to Use?
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000PyGjkIAF

Visualforce Security
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000PwAdtIAF

VisualForce Counter Using <apex:Variable>
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRiPIAX

How to show sections of the page on mouse over, and hide them on mouse out?
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRhEIAX

Passing parameters from Visualforce page to Apex controller via <apex:param>
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000NPRhfIAH

Working With Related Objects
http://www.eltoro.it/apex/ArticleViewer?id=a07A000000T2QJEIA3

Tuesday, March 3, 2015

How to export data in Excel or PDF format using Visualforce

How to export data in Excel or PDF format using Visualforce
***********************************************************

=========================================================
To Download PDF VISUALFORCE Page
=========================================================

<apex:page controller="contactquery" showHeader="false" renderAs="pdf">
    <apex:pageBlock title="Export Results" >
        <apex:pageBlockTable value="{!cs}" var="contact">
            <apex:column value="{!contact.ID}"/>
            <apex:column value="{!contact.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

=========================================================
Download Excel VISUALFORCE Page
=========================================================

<apex:page controller="contactquery" contentType="application/vnd.ms-excel#SalesForceExport.xls" cache="true">
    <apex:pageBlock title="Export Results" >
        <apex:pageBlockTable value="{!cs}" var="contact">
            <apex:column value="{!contact.ID}"/>
            <apex:column value="{!contact.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>
</apex:page>

=========================================================
Query Controller (Query the data you need)
=========================================================

public class contactquery{
    public List<Contact> cs{get; set;}
    public contactquery()
    {
    cs = new List<Contact>();
       for (Contact c : [Select id, Name from Contact])
       {    
           cs.add(c);
       }
    }
}

***********************************************************
Thanks Salesforce Knowledge Article

Saturday, February 7, 2015

Salesforce Integration example

Salesforce POST Method Integration
===================================
/*
    In this example, we get the account name from any other platform or any other salesforce. If the insertion process is success, we send the response as 'success'.
 
    - 'postconnectform' - This is the URL for this class. We can call this class using this URL with session Id of this Org.  
        Ex: https://ap1.force.com/services/apexrest/postconnectform/
 
    - https://ap1.force.com - is salesforce org instance
        Note: we need to change the url form salesforce.com to force.com
 
    - /services/apexrest - standard syntax
*/

***************************************************
Example for inserting a Account with requested name
***************************************************

@RestResource(urlMapping='/postconnectform/*')
global class AccountForm {  
 
    public class AccountClass{
 
        public String Name;
     
    }
 
    @HttpPOST
    global static string postFormRegistration(){
     
          try{
     
            RestRequest req = RestContext.request;
            Blob body = req.requestBody;          
            String JSONString = body.toString();
            AccountClass RegCls = new AccountClass();
            RegCls = (AccountClass)JSON.deserialize(JSONString, AccountClass.class);
         
            if(RegCls != NULL){
                Account acc =  new Account();
                acc.Name = RegCls.Name;
                insert acc;
            }
        }catch(Exception e){
     
        }
        return 'success';
    }
}

-------------
Execution flow
--------------
 i) Create the above class in salesforce
 ii) Get the class map url
 iii) Get the sessionId (String SessionId = UserInfo.getSessionId();)
 iv) Open Advanced Rest Client
 v) Select POST Radio button
 vi) Select Form Tab
 vii) Enter the key as 'Authorization'
 viii) Enter the value as 'Bearer sessionId'
 ix) Click Raw tab
 x)Enter the data
    {
        "Name":"Test1234"
    }
  xi) Click Send

Salesforce GET Method Integration
==================================

***************************************************
Example for get the Accounts from salesforce
***************************************************

@RestResource(urlMapping='/getconnectform/*')
global class GetAccount {

    public class InnerClass2{
        public List<AccountClass> testIns;
    }
 
    public class AccountClass{
     
        public String AccId;
        public String Name;
     
    }
 
    @HttpGET
    global static string postFormRegistration(){
     
          try{
     
            RestRequest req = RestContext.request;
            List<Account> listAcc = [SELECT Id, Name FROM Account];
            List<AccountClass> ns = new List<AccountClass>();
            for(Account acc : listAcc){
                AccountClass ins = new AccountClass();
                ins.Name = acc.Name;
                ins.AccId = acc.Id;
                ns.add(ins);
            }
            return JSON.serialize(ns);
         
        }catch(Exception e){
         
        }
        return 'error';
    }
}

----------------
Execution flow
---------------
 i) Create the above class in salesforce
 ii) Get the class map url
 iii) Get the sessionId (String SessionId = UserInfo.getSessionId();)
 iv) Open Advanced Rest Client
 v) Select GET Radio button
 vi) Select Form Tab
 vii) Enter the key as 'Authorization'
 viii) Enter the value as 'Bearer sessionId'
 ix) Click Send button

Wednesday, January 21, 2015

Salesforce - Using Jquery DataTable for pagination and sorting in visualforce page

<apex:page showHeader="false" sidebar="false" controller="ControllerName"  standardStylesheets="false">
    
    <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.4/css/jquery.dataTables.css"></link>    
    <apex:includeScript value="https://code.jquery.com/jquery-1.11.1.min.js"/>
    <apex:includeScript value="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.min.js"/>    
    <apex:includeScript value="https://code.jquery.com/jquery-1.10.2.min.js"/>
    <apex:includeScript value="https://cdn.datatables.net/1.10.4/js/jquery.dataTables.js"/> 
      
    <apex:form >       
        <table id="projectTable" class="table-project" >
            <thead>
            <tr>                     
                <th> Project Name </th>                        
            </tr>
            </thead>
            <tbody>
// projectList - is controller List
            <apex:repeat value="{!projectList}" var="pro">
                <tr>                    
                    <td>
                            {!pro.Name}                       
                    </td>
                   
                </tr>
            </apex:repeat>
            </tbody>
        </table>
    </apex:form>    
    <script>
        var j$ = jQuery.noConflict();
        j$(document).ready(function() {
            $('#projectTable').DataTable(    
                {                    
                    "searching": false,
                    "lengthChange": false,
                    "pageLength": 25,
                    "info": false                  
                }         
            );
        } );
    </script>
    <!--
       // To sort the date column
       // [5] - is 5th column from 0 
                    "aoColumnDefs": [
                        { "sType": "date", "aTargets": [ 5 ] }
                     ]           
        //To seeting the width
        { "sWidth": "100px", "aTargets": [ 5 ] },
        { "sWidth": "100px", "aTargets": [ 4 ] },
        { "sWidth": "100px", "aTargets": [ 3 ] }
    -->
</apex:page>

Monday, January 5, 2015

Salesforce code for Mass Update from List View

 Sample code for Opportunity

List view  Button Code

{!REQUIRESCRIPT("/soap/ajax/9.0/connection.js")}

var records = {!GETRECORDIDS( $ObjectType.Opportunity)};

if (records[0] == null ) {
    alert("Please select at least one record.")
} else {
    window.location = '/apex/OpportunityChangeStatus?Id=' + records;
}

Page

<apex:page standardController="Opportunity" extensions="OpportunityChangeStatus" recordSetVar="opp">
    <apex:form >
    <apex:pageBlock >
        <apex:pageBlockButtons >
            <apex:commandButton value="Save" action="{!save}"/>
            <apex:commandButton value="cancel" action="{!cancel}"/>
        </apex:pageBlockButtons>
        <apex:pageBlockSection >
            <apex:pageBlockSectionItem >
                <apex:outputLabel > Select a stage:</apex:outputLabel>
                <apex:inputField value="{!oppRec.StageName}"/>
            </apex:pageBlockSectionItem>    
        </apex:pageBlockSection>
    </apex:pageBlock>
    </apex:form>
</apex:page>

Controller

public class OpportunityChangeStatus {
    
    public Opportunity oppRec{get;set;}
    List<Opportunity> oppList = new List<Opportunity>();
    List<String> oppIdList = new List<String>();
    List<Opportunity> updatedOppList = new List<Opportunity>();
    
    public OpportunityChangeStatus(ApexPages.StandardController controller) {
        
    }
    
    private ApexPages.StandardSetController standardController;
    public OpportunityChangeStatus(ApexPages.StandardSetController standardController){
        oppRec = new Opportunity();        
        String oppId = ApexPages.currentPage().getParameters().get('id');
        oppIdList = oppId.split(',');       
    }
    public Pagereference save(){    
        
        for(String oppId : oppIdList){
            Opportunity opp = new Opportunity();
            opp.Id = oppId;
            opp.StageName = oppRec.StageName;
            updatedOppList.add(opp);
        }        
        if(updatedOppList.size() > 0){
            update updatedOppList;
        }        
        return new PageReference('/006');
    }
}

Salesforce Useful URL's - Part II


How to Customize the Lead Conversion Process in Salesforce.com

http://bulkified.com/How+to+Customize+the+Lead+Conversion+Process+in+Salesforce.com

Bulk attachment, content and document migration using Apex Dataloader

http://bulkified.com/Bulk+attachment%2c+content+and+document+migration+using+Apex+Dataloader

Preventing focus of first input field and Calendar widget on page load in Salesforce

http://bulkified.com/Preventing+focus+of+first+input+field+and+Calendar+widget+on+page+load+in+Salesforce

Salesforce How to Debug / Troubleshoot using the Salesforce Debug Logs

http://nickforce.blogspot.in/2011/11/salesforce-how-to-debug-troubleshoot.html#more

Visualforce component basic examples 

http://nickforce.blogspot.in/2011/04/visualforce-component-basic-examples.html#more

Salesforce - Generate dynamic inner query to fetch parent and related child records

Use Case: In many scenarios, we need to clone the records with related child records. Issue / Limitation: We may simply use the "cl...