function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
jjvdevjjvdev 

What is the best way to process selected records in a VF page using a custom list button

Have a need to add a custom list button to a visualforce page with a custom controller to process selected records in the list selectedContacts.  What is the most efficient way to do this?  Clicking the custom list button should use the records that are selected.

Custom controller example:
public class wrapperClassController {

	//Our collection of the class/wrapper objects cContact 
	public List<cContact> contactList {get; set;}

	//This method uses a simple SOQL query to return a List of Contacts
	public List<cContact> getContacts() {
		if(contactList == null) {
			contactList = new List<cContact>();
			for(Contact c: [select Id, Name, Email, Phone from Contact limit 10]) {
				// As each contact is processed we create a new cContact object and add it to the contactList
				contactList.add(new cContact(c));
			}
		}
		return contactList;
	}


	public PageReference processSelected() {

                //We create a new list of Contacts that we be populated only with Contacts if they are selected
		List<Contact> selectedContacts = new List<Contact>();

		//We will cycle through our list of cContacts and will check to see if the selected property is set to true, if it is we add the Contact to the selectedContacts list
		for(cContact cCon: getContacts()) {
			if(cCon.selected == true) {
				selectedContacts.add(cCon.con);
			}
		}

		// Now we have our list of selected contacts and can perform any type of logic we want, sending emails, updating a field on the Contact, etc
		System.debug('These are the selected Contacts...');
		for(Contact con: selectedContacts) {
			system.debug(con);
		}
		contactList=null; // we need this line if we performed a write operation  because getContacts gets a fresh list now
		return null;
	}


	// This is our wrapper/container class. A container class is a class, a data structure, or an abstract data type whose instances are collections of other objects. In this example a wrapper class contains both the standard salesforce object Contact and a Boolean value
	public class cContact {
		public Contact con {get; set;}
		public Boolean selected {get; set;}

		//This is the contructor method. When we create a new cContact object we pass a Contact that is set to the con property. We also set the selected value to false
		public cContact(Contact c) {
			con = c;
			selected = false;
		}
	}
}

Visualforce page example:
<apex:page controller="wrapperClassController">
    <apex:form >
        <apex:pageBlock >
            <apex:pageBlockButtons >
                <apex:commandButton value="Process Selected" action="{!processSelected}" rerender="table"/>
            </apex:pageBlockButtons>
            <!-- In our table we are displaying the cContact records -->
            <apex:pageBlockTable value="{!contacts}" var="c" id="table">
                <apex:column >
                    <!-- This is our selected Boolean property in our wrapper class -->
                    <apex:inputCheckbox value="{!c.selected}"/>
                </apex:column>
                <!-- This is how we access the contact values within our cContact container/wrapper -->
                <apex:column value="{!c.con.Name}" />
                <apex:column value="{!c.con.Email}" />
                <apex:column value="{!c.con.Phone}" />
            </apex:pageBlockTable>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Custom list button to be added example:
{!REQUIRESCRIPT("/soap/ajax/13.0/connection.js")} 

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

if (records[0] == null)   { 
   alert("Please select at least one row");
} 
else  { 


	 if(records.length==1)	{
	 
		  var state = {};
	
	      var callback = {
	          onSuccess: findContact,
	          onFailure: queryFailed,
	          source: state};
	
	      sforce.connection.query(
	          "Select Email, Name, AccountID From Contact where id='" + records[0] + "'",
	           callback);
	
	 } else	{


	     var where_clause = "";
	
	     for (var n=0; n<records.length; n++) { 
	
	         where_clause+=(where_clause.length>0?" or ":"") + "id='" +  records[n] + "'";
	     }
	
	      var state = {};
	
	      var callback = {
	          onSuccess: layoutResults,
	          onFailure: queryFailed,
	          source: state};
	
	      sforce.connection.query(
	          "Select Email, Name From Contact where " + where_clause,
	           callback);
	 }

} 

  function queryFailed(error, source) {
    alert("An error has occurred: " + error);
  }

 function layoutResults(queryResult, source) {

    if (queryResult.size == 0) return;
    
      var records = queryResult.getArray('records');
    
      var count = 0;

      var params = "company=" + escape(getContactListName()+" List View Blast - {!Today} "); 

      for (var i = 0; i < records.length; i++) {

        var contact= records[i];

        if(contact.Email=='' || contact.Email==null)    continue;

         var name = contact.Name.replace(",", "");

         params+=(params.length>0?"&":"") + "email=" + escape(name  + " <" + contact.Email + ">");
 
        count++;

      }

     if(count==0)  {

            alert("No selected rows contain email addresses");
            return;
      }


     var url = "http://clearslide.com/manage/email/external_link?" + params;;

     if(url.length>2000)  {

            alert("Too many items are selected at once.  Please enter the addresses directly into ClearSlide.");
            return;
      }


     //alert(url );

     window.open(url);

  }
  
  

 //////// single contact selected - look up account for company name

 function findContact(queryResult, state) {

      if (queryResult.size == 0) return;
    
      var records = queryResult.getArray('records');

     state["Email"] = records[0].Email;
     state["Name"] = records[0].Name;

        if(state["Email"]=='' || state["Email"]==null)    {

                alert("This contact has no email address");
                return;
        }


        state["Name"] = state["Name"] .replace(",", "");

      var callback = {
          onSuccess: findAccount,
          onFailure: queryFailed,
          source: state};

      sforce.connection.query(
          "Select Name From Account where id='" + records[0].AccountId + "'",
           callback);

  }



  
 function findAccount(queryResult, state) {

      var params = "";

    if (queryResult.size > 0) {
    
    	var records = queryResult.getArray('records');
    
        params = "company=" + escape(records[0].Name);
    }
   
  	var email =   state["Email"];
 	var name =   state["Name"];

    if(email!='' && email!=null)    params += (params.length>0?"&":"") +"email=" + escape(name + " <" + email + ">"); 
    else                            params += (params.length>0?"&":"") +"name=" + escape(name);

     var url = "http://clearslide.com/manage/email/external_link?" + params;

     //alert(url );

     window.open(url); 

 }

function getContactListName() { 
try { 
var a = document.getElementsByTagName("select"); 
for(var i = 0; i < a.length; i++) { 
if(a[i].name.indexOf("fcf", a[i].name.length - 3) !== -1) { 
return "'" + a[i].options[a[i].selectedIndex].text + "'"; 
} 
} 
} catch(e) {} 
return "Salesforce"; 
}