How to create custom button “Delete” and add it on a List View

Request is to create a custom button “Delete” and add it on a List View. (Scenario below is for the Account Object): Steps are:

  1. Go to Setup | Create | Objects
  2. Click on the name of the Object
  3. Scroll down to the Buttons, Links & Actions section.
  4. Click on New Button or Link
  5. Name it as Delete
  6. Select the Display Type: List Button 
  7. Do check the option: Display Checkboxes (for Multi-Record Selection)
  8. Behaviour: Execute JavaScript
  9. Content Source: OnClick JavaScript
  10. Following code:
{!REQUIRESCRIPT('/soap/ajax/29.0/connection.js')}
try
{
  var selectedRecords = {!GETRECORDIDS( $ObjectType.account )};
  if(selectedRecords.length<1)
    alert('Please Select at Least One Row !');
  else
  {
    userConsent = confirm(
        selectedRecords.length + 
        ' Record(s) will be Deleted. Continue ? '
      );
    if(userConsent == true)
    {
      delResult = sforce.connection.deleteIds(selectedRecords);
      if (delResult[0].getBoolean("success"))
      {
        alert('The Record(s) were Deleted Successfully.'); 
        window.location.reload();
      }
      else
        alert(
          'The Record(s) Could Not be Deleted. Error Message: ' + 
          delResult[0].errors.message
        );
    }  
  }
}
catch(e)
{
  alert('The Action Could not be Completed. Error Message: ' + e);
}

  1. Select Save

Now, we need to add it to the List View. Here you go:

  1. Go to Setup | Create | Objects
  2. Click on the Name of the Object
  3. Scroll down to Search Layouts section
  4. Click Edit next to List View Layout
  5. Move our new button from the Available Buttons to the Selected Buttons List
  6. Select Save
  7. Navigate to the Account tab and select a List View.

Note: As mentioned the above scenario refers to the Account Object. To add a delete button in the Opportunity object change the code from:

var selectedRecords = {!GETRECORDIDS( $ObjectType.account )}; to "var selectedRecords = {!GETRECORDIDS( $ObjectType.aopportunity )};"