Play Games

Search This Blog

Wednesday, August 27, 2014

Display Salesforce Data in the form of Chart(pie chart,bar chart etc) in visualforce page

We can display salesforce data in the form of pie chart,bar chart etc in visualforce page.
Example
Apex Class:
global with sharing class GoogleChartsController {
    
    /**
      Loads most recent 10 Opportunities
    */
    @RemoteAction  
    global static Opportunity[] loadOpps() {
        return [select Id, Name, ExpectedRevenue, Amount from Opportunity order by CreatedDate DESC limit 10];
    }  

}

Visualforce Page :
<apex:page controller="GoogleChartsController" sidebar="false">
    <!-- Google API inclusion -->
    <apex:includeScript id="a" value="https://www.google.com/jsapi" />
    
    <apex:sectionHeader title="Google Charts + Javascript Remoting" subtitle="Demoing - Opportunities by Exepected Revenue"/>

    <!-- Google Charts will be drawn in this DIV -->
    <div id="chartBlock" />
    
    <script type="text/javascript">
        // Load the Visualization API and the piechart package.
        google.load('visualization', '1.0', {'packages':['corechart']});
      
        // Set a callback to run when the Google Visualization API is loaded.
        google.setOnLoadCallback(initCharts);
  
        function initCharts() {        
          // Following the usual Remoting syntax
          // [<namespace>.]<controller>.<method>([params...,] <callbackFunction>(result, event) {...}
          // controller : GoogleChartsController
          // method : loadOpps
          GoogleChartsController.loadOpps(
                 function(result, event){ 
                     // load Column chart
                     var visualization = new google.visualization.ColumnChart(document.getElementById('chartBlock'));
                     // Prepare table model for chart with columns
                     var data = new google.visualization.DataTable();
                     data.addColumn('string', 'Opportunity');
                     data.addColumn('number', 'Expected Revenue');
                     data.addColumn('number', 'Amount');   
                     // add rows from the remoting results
                     for(var i =0; i<result.length;i++){
                        var r = result[i];
                        data.addRow([r.Name, r.ExpectedRevenue, r.Amount]);
                      }
                    // all done, lets draw the chart with some options to make it look nice.
                    visualization.draw(data, {legend : {position: 'top', textStyle: {color: 'blue', fontSize: 10}}, width:window.innerWidth,vAxis:{textStyle:{fontSize: 10}},hAxis:{textStyle:{fontSize: 10},showTextEvery:1,slantedText:false}});
              }, {escape:true});
          }
    </script>
</apex:page>

Output:



SlideShow in Visualforce Page

<apex:page >
<html>
<script type="text/javascript">
var slideimages=new Array()
function slideshowimages()
{

     for (i=0;i<slideshowimages.arguments.length;i++){
         slideimages[i]=new Image()
         slideimages[i].src=slideshowimages.arguments[i]
    }
}
</script>

<img src="{!$Resource.image2}" alt="Slideshow Image Script" title="Slideshow Image Script" name="slide" border="0" width="200" height="200"/><a href="http://hscripts.com" style="text-decoration:none;cursor:pointer;font-size:12px;color:green;">H</a>
<script type="text/javascript">
slideshowimages("{!$Resource.image2}","{!$Resource.image1}")
var slideshowspeed=2000
var whichimage=0
function slideit()
{
     if (!document.images)
           return
     document.images.slide.src=slideimages[whichimage].src
     if (whichimage<slideimages.length-1)
              whichimage++
     else
              whichimage=0
      setTimeout("slideit()",slideshowspeed)
}
 slideit()
</script>
<!-- Script by hscripts.com -->
</html>
</apex:page>
Note: Replace image urls.


snow fall effect in visualforce page

Visualforce Page Code:

<apex:page showHeader="false" sidebar="false">
<html>
<script>
 /*   Free Script provided by HIOXINDIA            */
/*   visit us at http://www.hscripts.com     */
/*   This is a copyright product of hioxindia.com */

var image="{!$Resource.snowfall}";  //Image path should be given here
var no = 15; // No of images should fall
var time = 0; // Configure whether image should disappear after x seconds (0=never):
var speed = 70; // Fix how fast the image should fall
var i, dwidth = 900, dheight =500;
var nht = dheight;
var toppos = 0;

if(document.all){
    var ie4up = 1;
}else{
    var ie4up = 0;
}

if(document.getElementById && !document.all){
    var ns6up = 1;
}else{
    var ns6up = 0;
}

function getScrollXY() {
  var scrOfX = 10, scrOfY = 10;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY =window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement &&
      ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
   scrOfY = document.documentElement.scrollTop;
   scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

var timer;

function ranrot()
{

var a = getScrollXY()
if(timer)
{
    clearTimeout(timer);
}
toppos = a[1];
dheight = nht+a[1];
//alert(dheight);

timer = setTimeout('ranrot()',2000);
}
   
ranrot();
   
function iecompattest()
{
    if(document.compatMode && document.compatMode!="BackCompat")
    {
        return document.documentElement;
    }else{
        return document.body;
    }
   
}
if (ns6up) {
    dwidth = window.innerWidth;
    dheight = window.innerHeight;
}
else if (ie4up) {
    dwidth = iecompattest().clientWidth;
    dheight = iecompattest().clientHeight;
}

nht = dheight;

var cv = new Array();
var px = new Array();       //position variables
var py = new Array();      //position variables
var am = new Array();     //amplitude variables
var sx = new Array();    //step variables
var sy = new Array();   //step variables

for (i = 0; i < no; ++ i) { 
    cv[i] = 0;
    px[i] = Math.random()*(dwidth-100);  // set position variables
    py[i] = Math.random()*dheight;     // set position variables
    am[i] = Math.random()*20;         // set amplitude variables
    sx[i] = 0.02 + Math.random()/10;  // set step variables
    sy[i] = 0.7 + Math.random();    // set step variables
    document.write("<div id=\"dot"+ i +"\" style=\"POSITION: absolute; Z-INDEX: "+ i +"; VISIBILITY: visible; TOP: 15px;LEFT: 15px;\"><img src='"+image+"' border=\"0\"><\/div>");
}

function animation() {  // animation function
    for (i = 0; i < no; ++ i) {  // iterate for every dot
        py[i] += sy[i];
            if (py[i] > dheight-50) {
                px[i] = Math.random()*(dwidth-am[i]-100);
                py[i] = toppos;
                sx[i] = 0.02 + Math.random()/10;
                sy[i] = 0.7 + Math.random();
            }
            cv[i] += sx[i];
            document.getElementById("dot"+i).style.top=py[i]+"px";
            document.getElementById("dot"+i).style.left=px[i] + am[i]*Math.sin(cv[i])+"px"; 
        }
        atime=setTimeout("animation()", speed);

}

function hideimage(){
    if (window.atime) clearTimeout(atime)
        for (i=0; i<no; i++)
            document.getElementById("dot"+i).style.visibility="hidden"
}
if (ie4up||ns6up){
animation();
if (time>0)
    setTimeout("hideimage()", time*1000)
}
animation();

/*   Free Script provided by HIOXINDIA            */
/*   visit us at http://www.hscripts.com     */
/*   This is a copyright product of hioxindia.com */
</script>
</html>
</apex:page>
Note : Place any image you like in static resource and change image url in this line
var image="{!$Resource.snowfall}";


Debug Logs in Salesforce

A debug log can record database operations, system processes  and errors that occur
when executing a transaction or running unit tests.

Debug logs can contain information about:

1)Database changes
2)HTTP callouts
3)Apex errors
4)Resources used by Apex
5)Workflow rules
6)Assignment rules
7)Approval processes
8)Validation rules

Setting Debug Log :
step 1: Go to setup--> Monitoring -->Debug logs or Logs-->Debug Logs
step 2: click new and then select any user and then click save.

viewing Debug Logs: when you run visualforce pages/classes or any other processes,
debug logs are created and we can view them in debug logs page.


Multiple tabs in visualforce page

visualforce page code:

  <apex:page id="thePage">
    <apex:tabPanel switchType="client" selectedTab="name2" id="theTabPanel">
        <apex:tab label="One" name="name1" id="tabOne">content for tab one</apex:tab>
        <apex:tab label="Two" name="name2" id="tabTwo">content for tab two</apex:tab>
    </apex:tabPanel>
</apex:page>
  
Output:

          







If you want to include visualforce pages in tabs ,the following code helps you.
Here Page1 and Page2 are visualforce pages
<apex:page >
    <apex:tabPanel >
        <apex:tab label="First Tab">
            <apex:include pageName="Page1"/>
        </apex:tab>
        <apex:tab label="second Tab">
            <apex:include pageName="Page2"/>
        </apex:tab>
    </apex:tabPanel>
</apex:page>

Batch Apex in Salesforce

Batch Apex in Salesforce

Batch Jobs : What is the need ?

       As you all might know about the salesforce governor limits on its data. When you want to fetch thousands of records or fire DML on thousands of rows on objects it is very complex in salesforce and it does not allow you to operate on more than certain number of records which satisfies the Governor limits.
But for medium to large enterprises, it is essential to manage thousands of records every day. Adding/editing/deleting them when needed.
There is a  powerful concept called Batch Apex. Batch Apex allows you to handle more number of records and manipulate them by using a specific syntax.
The execution logic of the batch class is called once for each batch of records. The default batch size is 200 records. You can also specify a custom batch size.
Batch job are made to perform common UPSERT operation on a scheduled basis. The Batch apex can be used to conveniently perform time to time task and some real complex job ranging from data cleansing, archiving the data to the other quality improvements.
Advantages:
  • A large number of records can be processed. Even batch size is changeable.
  • Result of one batch cannot affect other batch.It means every batch is descrete.
  • Each batch execution is considered a discrete transaction. With each new batch of records, a new set of governor limits is in effect. In this way, it’s easier to ensure that your code stays within the governor execution limits.
  • Another benefit of discrete batch transactions is to allow for partial processing of a batch of records in case one batch fails to process successfully, all other batch transactions aren’t affected and aren’t rolled back if they were processed successfully.
How to Implement:
Develop Apex class implementing 'Batchable' Interface. This interface has three operation defined to it. In order to implement batch processing, first we need to create an Apex class that implements Database.Batchable<sObject> interface.
This interface demands for three methods to be implemented:
Start - Use this to basically collect the records and then pass on to execute method
Execute-  Use this to process the records.
Finish - Called once, when processing get finished and can be used for operations like sending confirmation email
Lets jump to code, for better understanding.
Example:
Global class batchAccountUpdate implements Database.Batchable<sObject> {
   Global Database.QueryLocator start(Database.BatchableContext BC) {
       String query = 'SELECT Id,Name FROM Account';
       return Database.getQueryLocator(query);
   }   
   Global void execute(Database.BatchableContext BC, List<Account> scope) {
        for(Account a : scope) {
a.Name = a.Name + 'Updated';            
        }
        update scope;
   }   
   Global void finish(Database.BatchableContext BC) {
AsyncApexJob a = [SELECT Id, Status, NumberOfErrors,
JobItemsProcessed,TotalJobItems, CreatedBy.Email
FROM AsyncApexJob WHERE Id =:BC.getJobId()];
String UserEmail = 'Any EMAIL';
Messaging.SingleEmailMessage mail = new      Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {UserEmail});
mail.setReplyTo('ANY EMAIL');
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Batch Process has completed');
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }
}

How to run Batch Process:

In order to run batch process, you need to use
Database.executeBatch() method.
Open the developer console and then write a small snippet of apex code as shown below
batchAccountUpdate batchJob = new batchAccountUpdate();
Database.executeBatch(batchJob);
Scheduling Batch Process:
We can also schedule batch apex. In order to schedule batch class,we need to write schedulable batch class.
Example:
Global class batchAccountUpdateSchedular implements Schedule
{
Global void execute(SchedulableContext sc)
{
          batchAccountUpdate b= new batchAccountUpdate();
  Database.executebatch(b);
}
}
Now you can schedule this apex class by using Schedule Apex in Salesforce.

Tuesday, August 26, 2014

List Views in salesforce

List Views in salesforce

Sample code to display list view of account object in visualforce page

<apex:page showHeader="true" tabstyle="Account">
    <apex:ListViews type="Account" />
    <apex:ListViews type="Account" />
</apex:page>


The output will be as shown in the image below.


Date picker in Visualforce page

Date picker in Visualforce page

The following is the sample code to display date picker in visualforce page

<apex:page >
<apex:form >
<table>
<td> Date<br></br><input id="t" name="datee" onfocus="DatePicker.pickDate(false,
't', false);" size="12" tabindex="28" type="text" />
<span class="dateFormat"  style="display:none">[&nbsp;

<a href="javascript&colon;DatePicker.insertDate('', 't', true);"
>2/3/2011</a>&nbsp;]</span></td>
</table>
</apex:form>
</apex:page>

The output will be as shown in the image given below