Monday 31 October 2011

Mass Delete Button for Standard and Custom objects.

i created  custom button(Mass Delete)  for standard and custom objects.Using Data loader only Delete the all records in custom objects but i created Custom button for Delete all the records in custom object. select all the records click on  Mass Delete  button then Deleted all the records at a time.
This is very useful code working perfectly

Mass Delete.
========
{!REQUIRESCRIPT("/soap/ajax/10.0/connection.js")}

var idsToDelete = {!GETRECORDIDS( $ObjectType.Contact )};
var deleteWarning= 'Are you sure you wish to delete ' +idsToDelete.length+ ' Records?';
if(idsToDelete.length&& (window.confirm(deleteWarning)))
{
sforce.connection.deleteIds(idsToDelete,function()
{navigateToUrl(window.location.href);
});
}
else if (idsToDelete.length == 0)
{
alert("Please select the contacts you wish to delete.!!");
}

Sunday 30 October 2011

Automatic Lead Coversion To Opportunity,Account and Contact based on Lead Status

I got new requirement in  Sales force  project.My Client ask new thing i.e  Automatic Lead Conversion To Opportunity based on Lead Status. i worked this task that time i Struggle but finally i finish this task.

here i am using trigger for Automatic Lead Conversion To Opportunity,Account and Contact  based on Lead Status.In Lead Status i  Created new value i.e "Set Appointment". User fills the Lead information that time choose Lead Status is "Set Appointment" after click on Save button then  Lead  converts Automatically  To Opportunity,Account and Contact.This code working newly  create Lead   and   Update  Lead also.



This is very useful code perfectly working.

Trigger :

............

trigger triggerConvertLead on Lead (after insert, after update)
{
  System.debug('Trigger Insert'+ Trigger.isInsert);
  System.debug('Trigger Update'+ Trigger.isUpdate);
  
 if(Trigger.isInsert && Trigger.new[0].Status == 'Set Appointment') {
   System.debug('Trigger Insert'+ Trigger.isInsert);
   System.debug('Trigger Update'+ Trigger.isUpdate);
  //System.debug('Trigger Upsert'+ Trigger.isUpdate);
 if((!Trigger.isInsert && (Trigger.new[0].Status == 'Set Appointment' && Trigger.old[0].Status != 'Converted' &&
     Trigger.new[0].Status !='Converted'))||
   (Trigger.isInsert && Trigger.new[0].Status == 'Set Appointment' && Trigger.new[0].Status != 'Converted')){      
        Database.LeadConvert lc = new database.LeadConvert();
        lc.setLeadId(Trigger.new[0].Id);
        LeadStatus convertstatus = [select Id, MasterLabel from LeadStatus where IsConverted= true limit 1];
        lc.setConvertedStatus(convertStatus.MasterLabel);
        Database.LeadConvert[] lcArray = new Database.LeadConvert[] {lc};
        Database.LeadConvertResult[] results = Database.convertLead(lcArray);
        System.assert(results[0].IsSuccess());
     }
     else if(!Trigger.isUpdate && (Trigger.new[0].Status != 'Converted' ))
     {
   }
  }
 if(Trigger.isUpdate && Trigger.new[0].Status == 'Set Appointment')
  {
        //System.debug('Inside Trigger isUpdate ');
        //List<String> LeadNames = new List<String>{};
    for(Lead myLead: Trigger.new){
    if(myLead.IsConverted==false) {
    Database.LeadConvert lc = new database.LeadConvert();
         lc.setLeadId(myLead.Id);
         lc.convertedStatus = 'Set Appointment';
                //Database.ConvertLead(lc,true);
                //lc.setDoNotCreateOpportunity(true);
         Database.LeadConvertResult lcr = Database.convertLead(lc);
         System.assert(lcr.isSuccess());
           }
         }           //System.assert(results[0].IsSuccess());
      
      }
}

 i deployed this code from Sandbox to  Production for this purpose i write Test class to trigConvertLead.

Test Class:

 ....................

@isTest

  private class TestConvertLead {
    static testMethod void createLeadToConvert() {
      Lead newL = new Lead();
       newL.LastName = 'Test Lastname';
       newL.Company = 'Test Company';
       newL.Status = 'Set Appointment';
        insert newL;

    Lead newL2 = new Lead();
      newL2.LastName = 'Test Lastname';
      newL2.Company = 'Test Company';
      newL2.Status = 'Open';
        insert newL2;      
        //Lead UpdL = [Select Id from Lead where Id=: newL.Id];
    newL2.Status = 'Set Appointment';
        update newL2;

        Lead newL3 = new Lead();
    newL3.LastName = 'Test Lastname';
    newL3.Company = 'Test Company';
    newL3.Status = 'Open';
        insert newL3;      
        //Lead UpdL = [Select Id from Lead where Id=: newL.Id];
//    newL2.Status = 'Set Appointment';
//      update UpdL;

      
    //Lead Lead1 = [Select Id from Lead where Id=: newL.Id];
    List<Lead> listLead = [SELECT IsConverted, Status, Id FROM Lead WHERE Id =:newL3.Id limit 1];
  
    for(Lead l: listLead) {
      if(l.IsConverted==false) {
        Database.LeadConvert lc = new database.LeadConvert();
            lc.setLeadId(l.id);
            lc.convertedStatus = 'Set Appointment';
            Database.LeadConvertResult lcr = Database.convertLead(lc);
            System.assert(lcr.isSuccess());
      }
    }

     }
}

Tuesday 18 October 2011

Edit and Delete Command For Datatable In Visualforce

i write the Apex Class and Visual force Page for Edit and Delete the Records in Account Page.


Visual Force Page:

<apex:page controller="DataTableEditRemoveController">

<apex:form id="form" >
<apex:pageBlock title="Accounts">
  <apex:pageMessages ></apex:pageMessages>
  <apex:pageBlockTable value="{!accs}" var="row">
     <apex:column >
       <apex:outputLink title="" value="/{!row.id}/e?retURL=/apex/{!$CurrentPage.Name}" style="font-weight:bold">Edit</apex:outputLink>&nbsp;|&nbsp;
       <a href="javascript:if (window.confirm('Are you sure?')) DeleteAccount('{!row.Id}');" style="font-weight:bold">Del</a>
     </apex:column>
     <apex:column value="{!row.Name}"/>
     <apex:column value="{!row.BillingStreet}"/>
     <apex:column value="{!row.BillingCity}"/>
     <apex:column value="{!row.BillingPostalCode}"/>
     <apex:column value="{!row.BillingCountry}"/>
  </apex:pageBlockTable>
</apex:pageBlock>

<apex:actionFunction action="{!DeleteAccount}" name="DeleteAccount" reRender="form" >
   <apex:param name="accountid" value="" assignTo="{!SelectedAccountId}"/>
</apex:actionFunction>
</apex:form>
</apex:page>
 
How It Is Done For Edit Action:
Since the standard Account edit page is good enough for me I used an outputLink component to link the record to its Standard Edit page. In Salesforce for standard objects you can follow this format to get the URL for their edit page: /{RecordId}/e

I also wanted this to work in such a way that would return the user back to my Visualforce page once the user clicks on "save" or "cancel" in the Account edit page. In order to do that I need to add the following to the URL: /{RecordId}/e?retURL={returnURL}

In the Page's source code (above) you see that for return URL I have used {!$CurrentPage.Name} merge field, where I could simply put my page name. I like writing code clean! By doing this if you later on decided to change your page name, you do not need to worry about breaking anything! You page will continue to work with no problems!

How It Is Done For Delete Action:
In order to support this action in your page you need to do a bit of coding. The key is to be able to find out which account was selected by the user to be deleted.

In this example I have used a actionFunction component that triggers a Controller's Apex method call "DeleteAccount".

Before getting more into the coding part I wanted this link to get a confirmation from the user about deleting the record before actually we remove it.
In order to do so, we need to use a little bit of Javascript "window.confirm", the javascript function returns true if the user clicks on OK and false if the user selects "Cancel".

In order to capture the user's selection as to which account should be deleted I have added a "param" tag to the actionFunction component which passes the Account ID to the controller and as soon as user clicks on the link.
Now let's take a look at the code:
Controller :
public class DataTableEditRemoveController {

   public List<Account> accs { get; set; }
  
   //used to get a hold of the account record selected for deletion
   public string SelectedAccountId { get; set; }
  
   public DataTableEditRemoveController() {
       //load account data into our DataTable
       LoadData();
   }
  
   private void LoadData() {
       accs = [Select id, name, BillingStreet, BillingCity, BillingPostalCode, BillingCountry from Account limit 20];
   }
  
   public void DeleteAccount()
   {
      // if for any reason we are missing the reference 
      if (SelectedAccountId == null) {
      
         return;
      }
     
      // find the account record within the collection
      Account tobeDeleted = null;
      for(Account a : accs)
       if (a.Id == SelectedAccountId) {
          tobeDeleted = a;
          break;
       }
      
      //if account record found delete it
      if (tobeDeleted != null) {
       Delete tobeDeleted;
      }
     
      //refresh the data
      LoadData();
   }    
  
  
}

 

How to Write Good Test Coverage on Visualforce Pages

Once the development phase of your new Visualforce page is finished often many find it a challenge to receive the acceptable code coverage needed to be obtained in order to transport the changes into production instance of Sales force.

Below is a sample of how you can create a test class that will take care of it! This is going to be really interesting...

First i will show you the visual force page and the controller behind it.
What this page does is to simply filter the Account records by their type (picklist) and show them to the user.


Here i write Source Code for Visual force Page and its Controller.

Visual force Page:


<apex:page controller="myPageController" tabStyle="Account">
<apex:form >
<apex:sectionHeader title="My Page" />
<apex:pageBlock title="" id="pageBlock">
<apex:pageBlockButtons location="top">
<apex:inputField id="accountType" value="{!Account.Type}" />
<apex:commandButton value="View" action="{!ViewAccounts}" id="theButton" rerender="pageBlock"></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageMessages ></apex:pageMessages>
<apex:pageBlockTable value="{!accounts}" var="a" rendered="{!NOT(ISNULL(accounts))}">
<apex:column >
<apex:facet name="header">Account Name</apex:facet>
<apex:outputLink value="/{!a.Id}" target="_blank">{!a.Name}</apex:outputLink>
</apex:column>
<apex:column value="{!a.type}"></apex:column>
</apex:pageBlockTable>
</apex:pageBlock>
</apex:form>
</apex:page>

Controller :
public class myPageController {
private Account acc = new Account();
private List<Account> accs;
public Account getAccount()
{
return acc;
}
public void setAccount(Account a)
{
acc = a;
}
public List<Account> getAccounts()
{
return accs;
}
public PageReference ViewAccounts()
{
if (acc.Type == null)
{
//view a message because validation has failed.
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'Validation Failed: Select an item fron the dropdown list.'));
return null;
}
string AccountType = acc.Type;
accs = [Select id, name, type from Account where type= :AccountType limit 20];
if (accs == null || accs.size() == 0)
{
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.INFO,'No data found to be shown.'));
}
return null;
}
}



Now it is the moment! The most important part: the tester class.
In order to get a the best results following things should be included in your test method:
  • Create a reference to your page and set the Test object's current reference to your page (shown below)
  • Create a new instance of your controller (if you are using a Custom Controller or Extension)
  • Consider all possible scenarios (Test Cases) and try calling all properties and methods of your controller (Demonstrated below)
Test Class :

public class AccountCheck {
static testmethod void Account()
{
//Test converage for the myPage visualforce page
  PageReference pageref = Page.AccountCheckbox;
  Test.setCurrentPageReference(pageref);
// create an instance of the controller

  AccountCheckbox acc = new AccountCheckbox();
   //try calling methods/properties of the controller in all possible scenarios

// to get the best coverage
List<Account> selectedAccounts = new List<Account>();
  acc.getSelected();
  acc.GetSelectedAccounts();
  acc.getAccounts();
     }
    }


Tuesday 11 October 2011

Delete the Bad Leads in Salesforce.

How to Delete the Bad Leads in Salesforce.Bad Leads Means in Lead object  have Company Field.
Somany Websites Using Web2Lead.  Fill the Information in WebSite Click On Save button information is Stored into Lead Object.That time Defaultly Company Field is Stored the 'Google' Value.
So this is the Bad Leads here i Delete the Bad Leads after inserted based on Condition whenever Company Field  is Stored 'Google' that Record will be Deleted Automatically Using Apex Class and Trigger in Salesforce.

Apex Class:



public class DeleteLeads
{
 public static void addHelloWorld(Lead[] accs)
 {
 
 List<Lead> lead= [Select l.Company, l.Id from Lead l  WHERE l.Company ='Google'];
     //Id Lead1Id= Lead[0].Id;
     Lead lea = new Lead();
     lea.Company = 'Google';
     if(lea.Company =='Google')
        delete lead;
      else
      {
         insert lead;
     }
   }
   }

in above class i selected company name and id From Lead and Condition is
 if(lea.Company == 'Google')

after i Created Trigger for this Class

Trigger :
=========

trigger deletelead on Lead (after insert) {
if(trigger.isinsert){
List<Lead> lead = new List<Lead>();
DeleteLead.addHelloWorld(lead);
}
}
Here DeleteLead.addHelloWorld(lead) means  Class Name.Method Name(var)


So............Using Apex Class and Trigger I Prevent the Bad Leads in Salesforce.

Create the Manage Page For Custom Object.

Please Share the Subject with others. i created Manage Page for Custom obejct. Object Name is Talend and Created Some Fields in Talend object. Here i Created Apex Class and Visualforce page  for Talend Object.

Apex Class:   DataTableDelete

public class DataTableDelete {

public List<Talend__c> leas { get; set; }

   //used to get a hold of the account record selected for deletion
   public string SelectedtalendId { get; set; }

   public DataTableDelete() {
       //load account data into our DataTable
       LoadData();
   }

   private void LoadData()
   {
   
       leas = [Select t.Id,t.Name__c,t.Phone__c,t.Company__c from Talend__c t];
   }

   public void DeleteLead()
   {
      // if for any reason we are missing the reference
      if (SelectedtalendId== null)
      {
         return;
      }
      // find the account record within the collection
      Talend__c tobeDeleted = null;
      for(Talend__c t : leas)
       if (t.Id == SelectedtalendId)
       {
          tobeDeleted = t;
          break;
       }
   
      //if account record found delete it
      if (tobeDeleted != null) {
       Delete tobeDeleted;
      }
   
      //refresh the data
      LoadData();
   }
   

  }

Visual force Page: TalendManagePage

<apex:page controller="DataTableDelete">

<script>
var newWin=null;
    function openLookupPopup(id)
    {
        //alert(id);
        var url="/apex/talend1?idfield="+ id;
        newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
        if (window.focus)
        {
            newWin.focus();
        }
        return false;
    }
    function addopenLookupPopup()
    {
     
        var url="/apex/addtalend";
        newWin=window.open(url, 'Popup','height=500,width=600,left=100,top=100,resizable=no,scrollbars=yes,toolbar=no,status=no');
        if (window.focus)
        {
            newWin.focus();
        }
        return false;
    }
</script>
<apex:sectionHeader title="Talend Edit" subtitle="Talend"/>
<apex:form id="form" >
<apex:pageBlock title="Talend" id="pb1">
<apex:pageblockButtons location="Top">
     <apex:CommandButton value="Add"   onclick="addopenLookupPopup()"/>
</apex:pageblockButtons>
  <apex:pageMessages ></apex:pageMessages>
  <apex:pageBlockTable value="{!leas}" var="row">
  <apex:column >
  <apex:facet name="header">Name</apex:facet>
  <apex:outputLink value="/{!row.Id}" target="_blank">{!row.Name__c}</apex:outputLink>
  </apex:column>
     <apex:column value="{!row.Phone__c}"/>
     <apex:column value="{!row.Company__c}"/>
     <apex:column headerValue="Action">
 
      <a href="#" onclick="openLookupPopup('{!row.Id}'); return true" style="font-weight:bold">Edit</a>&nbsp;&nbsp;
      <a href="javascript:if (window.confirm('Are you sure?')) DeleteLead('{!row.Id}');" style="font-weight:bold">Del</a>
     </apex:column>
   
  </apex:pageBlockTable>
</apex:pageBlock>
<apex:actionFunction action="{!DeleteLead}" name="DeleteLead" reRender="form" >
   <apex:param name="leadid" value="" assignTo="{!SelectedtalendId}"/>
</apex:actionFunction>
</apex:form>
</apex:page>

See in Visual force Page here inside the  Script i used Edit and Add    Visual force Page URL .
i.e  var url="/apex/addtalend";
      var url="/apex/talend1?idfield="+ id;

For this Purpose  i Created another Apex Classes and Visual force Pages.

Edit Purpose :
============
Apex Class :


public class talend1
{
public talend1(ApexPages.StandardController Controller)
{
String ParentId = System.currentPageReference().getParameters().get('idfield');
}

Talend__c talend;
public Talend__c gettalend()
{
if(talend == null)
{
   //talend = new Talend__c();
   String recordidvalue= System.currentPageReference().getParameters().get('idfield');
   talend = [Select t.Id,t.Name__c,t.Opportunity__c,t.Phone__c,t.Account__c,t.Company__c from Talend__c t where t.Id=:recordidvalue];
}
return talend;
}
public PageReference Save1()
{
Talend__c t = new Talend__c();
 String eventid= System.currentPageReference().getParameters().get('idfield');
t = [Select t.Id,t.Name__c,t.Opportunity__c,t.Phone__c,t.Account__c,t.Company__c from Talend__c t where t.Id=:eventid];
t.Name__c = talend.Name__c;
t.Company__c = talend.Company__c;
t.Phone__c = talend.Phone__c;


update t;
return new PageReference('javascript:window.close()');

}

}

Visual force Page :
=============

<apex:page standardController="Talend__c" extensions="talend1" showHeader="false" sidebar="false">
<script language="javascript">

function closeMWindow()
{
newwin = window.open(location.href,'_parent','');
newwin.close();
}


</script>

<script>
function ConfirmCancel()
{
 var isCancel = confirm("Are u sure want Cancel");
 if(isCancel) return true;
 return false;
 }

</script>

<apex:sectionHeader title="Talend Edit" subtitle="Talend"/>
<apex:form >
<apex:pageBlock title="Talend" mode="Edit">
<apex:pageBlockButtons >

<apex:commandButton value="Save" action="{!Save1}"/>
<apex:commandButton value="Cancel" action="{!Cancel}"/>
<apex:commandButton onclick="closeMWindow();" value="Close Main window"></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockSection title="talend" columns="1">
<apex:inputfield value="{!talend.Name__c}"/>
<apex:inputfield value="{!talend.Company__c}"/>
<apex:inputfield value="{!talend.Phone__c}"/>
<apex:inputfield value="{!talend.Account__c}"/>
<apex:inputfield value="{!talend.Opportunity__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

This Apex Class and Visual force page is Update the Record in Talend Obejct.


Add Purpose :
============
Apex Class :


public with sharing class aatalend {

    public aatalend(ApexPages.StandardController controller)
    {

    }
  Talend__c talend;
public Talend__c gettalend()
{
if(talend == null)
{
   talend = new Talend__c();
}
return talend;
}
public PageReference Save1()
{
Talend__c t = new Talend__c();
t.Name__c = talend.Name__c;
t.Company__c = talend.Company__c;
t.Phone__c = talend.Phone__c;
t.Account__c = talend.Account__c;
t.Opportunity__c = talend.Opportunity__c;

insert t;
return new PageReference('javascript:window.close()');
}

}


Visual force Page :


<apex:page standardController="Talend__c" extensions="aatalend" showHeader="false" sidebar="false">
<script language="javascript">
function closeMWindow()
{
newwin = window.open(location.href,'_parent','');
newwin.close();
}
</script>

<script>
function ConfirmCancel()
{
 var isCancel = confirm("Are u sure want Cancel");
 if(isCancel) return true;
 return false;
 }
</script>

<apex:sectionHeader title="Talend Edit" subtitle="Talend"/>
<apex:form >
<apex:pageBlock title="Talend" mode="Edit">
<apex:pageBlockButtons >

<apex:commandButton value="Save" action="{!Save1}"/>
<apex:commandButton value="Cancel" action="{!Cancel}"/>
<apex:commandButton onclick="closeMWindow();" value="Close Window"></apex:commandButton>
</apex:pageBlockButtons>
<apex:pageBlockSection title="talend" columns="1">
<apex:inputfield value="{!talend.Name__c}"/>
<apex:inputfield value="{!talend.Company__c}"/>
<apex:inputfield value="{!talend.Phone__c}"/>
<apex:inputfield value="{!talend.Account__c}"/>
<apex:inputfield value="{!talend.Opportunity__c}"/>
</apex:pageBlockSection>
</apex:pageBlock>
</apex:form>
</apex:page>

This code is for newly add the Record in Talend Obejct.



These are all the Steps done Properly means Talend MangePage Working Properly. Talend ManagePage display like this.