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
SurjenduSurjendu 

Sending inputCheckBox values to controller

My code works like this. I have n number of Lead objects. When I click a checkbox I am trying to pass the value to a javascript function. It is not working. Any help. Also How do i achieve this functionality?

<apex:page controller="registerDomainController" tabStyle="Lead">
<script>
function addUsers(userid)
{
var idsToAdd = new Array();
alert('Before adding' + userid);
idsToAdd.add(userid);
}
</script>
<apex:sectionHeader title="Add User">
<apex:form>

<apex:pageBlock>
<apex:facet name="footer">

<apex:pageBlockSection title="Add Users to the Extranet">
<apex:dataTable value="{!allLeads}" var="user" cellspacing="0" cellpadding="4" border="0" width="800px">
<apex:column>
<apex:facet name="header">First Name</apex:facet>
<apex:outputText>{!user.firstname}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Last Name</apex:facet>
<apex:outputText>{!user.lastname}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Email Address</apex:facet>
<apex:outputText>{!user.email}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Phone number</apex:facet>
<apex:outputText>{!user.phone}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Add User</apex:facet>
<apex:inputCheckbox value="{!user.id}" onclick='addUsers({!user.id})'/>
</apex:column>

</apex:dataTable>

</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:sectionHeader>
</apex:page>
Best Answer chosen by Admin (Salesforce Developers) 
Tiwari_ShwetaTiwari_Shweta

Hi Jason,

 

I am working on the functionality of checkbox in datatable. On clicking the checkbox,I have to retrive the value of corresponding row.I have aceive this functionality by using wrapper class.

Is this possible to acieve the functionality without using wrapper class.

 

Can you please help.

All Answers

dchasmandchasman
There re a couple of issues with your page as it stands below but the main problem is that you are missing quotes around your js function call:

onclick='addUsers({!user.id})'

if you think about what this will turn into once the formula is evaluated you'll see what I mean:

onclick='addUsers(005xxxxxxxx)'

so you need it to look like this:

onclick="addUsers('{!user.id}')"

which will result in the correct expansion:

onclick="addUsers('005xxxxxxx')"

NOTE: there is a bug w.r.t. handling of single quotes for attribute values that we've fixed in the next release but for now stick to using double quotes to delimit attribute values.

Also, the use of apex:outputText with child {!}'s is superflous and will result in a compile time validation error in an upcoming release. Either drop the outputText's all together and just use the {!} alone (my recommendation unless you need to force expression results to not be escaped which is unwise from a XSS vulnerability perspective) or use the soon to be required <apex:outputText value> attribute like this:

<apex:outputText value="{!user.name}"/>



Message Edited by dchasman on 03-11-2008 08:58 PM
SurjenduSurjendu
Thanks...Can  u plz tell me how do I send the array of selected values from the javascript to my custom controller? Without that I wont be able to proceed forward.
dchasmandchasman
I think you are making this more complicated that it needs to be - you should be able to accomplish what you're trying to do without any javascript at all - visualforce's data binding and action binding support can handle all of this for you. I'll work up an example and post it here soon.




Message Edited by dchasman on 03-12-2008 08:54 AM
TehNrdTehNrd

dchasman wrote:
 I'll work up an example and post it here soon.


I would be very interested in this as well. Would this example be a dataTable with check boxes next to records (rows) and then based upon which records are checked you can perform some type of logic on the selected rows? Essentially, as they are checked and unchecked they are inserted and removed automatically from a object list in the controller?

I looked for something like this in the documentation but could find it. This type of example would be money.




Message Edited by TehNrd on 03-12-2008 12:29 PM
SurjenduSurjendu
Thanks again...Just to reiterate

I want a dataTable or a pageDataList  with check boxes next to records (rows) and then based upon which records are checked I want to send the values of the checked records  to my custom controller. My custom controller takes all the records, creates an XML and send the XML to an outside server.

Creating an XML and sending it to the server is done. I just need to collate all the values checked(checkboxes) by the user.
dchasmandchasman
What is the data type of your allLeads property (list or array of SObject of type Lead?). If you are currently binding to SObjects the trick to be able to augment them is to:

- create a small apex class wrapper around each sobject that mixes in your additional properties /or actions:

    public class LeadWrapper {
      public LeadWrapper(Lead delegate) {
        this.delegate = delegate;
      }
   
      public Lead getLead() {
        return delegate;
      }
   
      public void setSendToExternalService(boolean sendToExternalService) {
        this.sendToExternalService = sendToExternalService;
      }
   
      public boolean getSendToExternalService() {
        return sendToExternalService;
      }
   
      private final Lead delegate;
      private boolean sendToExternalService;
    }

- return a list of wrapped objects deom your controller's getter (getAllLeads() in this case)

VF data binding will now handle all the to and from bits and by the time your controller's sendToExternalService() action method is called you will have a collection of LeadWrapper objects that can each answer the "should I be sent the external service" question.



Message Edited by dchasman on 03-14-2008 08:44 AM
SurjenduSurjendu
Doug

I have few questions. When will I call SendToExternalService? How to I get the value in testController?? I mean on click of the commandButton I call a method called testSaveUsers. How do the method testSaveUsers in my controller class get the values.

Please help!!!!

My first Page:

<apex:page controller="testController" tabStyle="Lead">

<apex:sectionHeader title="Add User">
<apex:form>

<apex:commandButton action="{!testSaveUsers}" value="Add User" styleClass="btn" ></apex:commandButton>

<apex:pageBlock>
<apex:pageBlockSection title="Add Users to the Extranet">

<apex:dataTable value="{!allLeads}" var="user" cellspacing="0" cellpadding="4" border="0" width="800px">
<apex:column>
<apex:facet name="header">First Name</apex:facet>
<apex:outputText>{!user.lead.firstname}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Last Name</apex:facet>
<apex:outputText>{!user.lead.lastname}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Email Address</apex:facet>
<apex:outputText>{!user.lead.email}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Phone number</apex:facet>
<apex:outputText>{!user.lead.phone}</apex:outputText>
</apex:column>
<apex:column>
<apex:facet name="header">Add User</apex:facet>
<apex:inputCheckbox value="{!user.lead.id}" /> should I be using the onSelect={user.sendToExternalService}
</apex:column>

</apex:dataTable>

</apex:pageBlockSection>

</apex:pageBlock>
</apex:form>
</apex:sectionHeader>
</apex:page>

************************************************************************************

public class testController
{
List<LeadWrapper> listOfLeadWrappers = new List<LeadWrapper>();
List<LeadWrapper> selectedLeadWrappers = new List<LeadWrapper>();
public List<LeadWrapper> getAllLeads()
{
Lead[] allLeads = [select id,firstname,lastname,email,phone from Lead];
for(Lead l : allLeads)
{
LeadWrapper wrapper= new LeadWrapper(l);
listOfLeadWrappers.add(wrapper);
}
return listOfLeadWrappers;
}

public PageReference testSaveUsers()
{
for(LeadWrapper lw : listOfLeadWrappers)
{
if(lw.getSendToExternalService())
{
selectedLeadWrappers.add(lw);
}
}
return Page.RetrieveValues;
}

public List<LeadWrapper> getAllSelectedLeadWrappers()
{
return selectedLeadWrappers;
}

}

SurjenduSurjendu
Hey Doug

Figured it out. Thanks a ton for the help.

Regards
surjendu
TehNrdTehNrd
Could you please post your final code.

I would also recommend using the SRC functionality when replying with code. That way it won't get all garbled. When typing a reply it is the button that says SRC.


Message Edited by TehNrd on 03-14-2008 02:09 PM
TehNrdTehNrd
Unfortunetly for me the talk of a wrapper class kind of slipped over my head.

Could I get some more pointers/instructions of how I could add a check box in a contact dataTable and then have this reflected in my collection of contacts in the controller. Here is what I've got so far which is only a super simple controller and a dataTable.

Page:
Code:
<apex:page controller="contacts">
        <apex:panelGrid columns="1" id="theGrid" width="50%" >
        <apex:pageBlock>
        
        <apex:dataTable value="{!Contacts}" var="con" styleClass="list">
                <apex:column>
                        <apex:facet name="header">Name</apex:facet>
                        <apex:outputText value="{!con.Name}"/>
                </apex:column>
                <apex:column>
                        <apex:facet name="header">Phone</apex:facet>
                        <apex:outputText value="{!con.Phone}"/>
                </apex:column>
                <apex:column>
                        <apex:facet name="header">Mailing City</apex:facet>
                        <apex:outputText value="{!con.MailingCity}"/>
                </apex:column>
        </apex:dataTable>
        
        </apex:pageBlock> 
        </apex:panelGrid>
</apex:page>

Controller:
Code:
public class contacts {

        Contact [] Contacts;

        public List<Contact> getContacts(){
                if(contacts == null){
                        contacts = [select Id, Name, Phone, MailingCity from Contact limit 10];
                } 
                return Contacts;
        }
}

 
I know that since the dataTable can only display values from the given object, in this case Contact, I need to trick it into thinking that a checkbox (boolean value) is a field on Contacts but I'm not sure about how to approach this so and help is greatly appreciated.

Thanks,
Jason



Message Edited by TehNrd on 03-18-2008 03:27 PM
kmccollkmccoll
I have a challenge similar to this, so I figured it would be better to bring this thread back to life rather than post a new thread.

My page has two lists (pageBlockLists) - contacts on the top and activities on the bottom.  The goal is that when the checkboxes are selected on the contacts, the bottom pageBlock with the activities re-renders showing activities for all of the selected contacts.  I am struggling to get the selected status back to the controller.  The re-render is intended to be an ajax action triggered by the clicking of the checkbox - no submit button.

I've created a wrapper class to contain the contact plus the selected status, but can't seem to get the checked status of the checkbox back to the controller automatically.   Using the onchange event of the checkbox I can fire actionsupport or actionfunction and get the re-render to happen, but not with an updated list of contacts.

I think I'm probably missing something pretty obvious - anybody help me out with the best way of doing this?

Here's my relevant code:
wrapper class: (note: still on spring 08)
Code:
public class contactInList {
 
 public Contact contact;
 public Boolean  selected;
 
...
 
 public Contact getContact() { return contact; }
 public Boolean  getSelected(){ return selected; }
...
 
 public void setContact( Contact c ) { this.contact = c; }
 public void  setSelected( Boolean b ) { this.selected = b; }
... 
}

 relevant parts of the controller:
Code:
public class contactCallListController {
 
 List<ContactInList> contactList;
 List<Id> selectedContacts = new List<Id>();
 
...
 public void selectContacts()
 {
  selectedContacts.clear();
    
  for ( ContactInList c: contactList )
  {
   if (c.selected)
   {
    selectedContacts.add(c.Contact.Id);
   } 
  }
  selectedContactsSize = selectedContacts.size();
 }
... 
 public List<Task> getMostRecentActivities()
 {
  
  List<Task> activities;
  
  activities = [ SELECT Id,
      Subject, 
      Who.Name,
      ActivityDate, 
      Days_Ago__c, 
      Friendly_Date__c,
      Owner.Name,
      Type
    FROM Task
    WHERE WhoId IN :selectedContacts
    ORDER BY ActivityDate DESC
    LIMIT 5 ];
  
  return activities;
 }
}

 
And then the page:
Code:
...

function setSelectedContacts()
{
... code to visually highlight the rows and then call to actionFunction...

 apex_selectContacts();
}

...

<apex:pageBlock title="Call List" id="pbCallList">

 <apex:pageBlockList value="{!ContactList}" var="each" id="pblContactList" >
  
  <apex:column> 
   <apex:form>
     <apex:inputCheckbox value="{!each.selected}" onchange="setSelectedContacts();" />
     <apex:actionFunction id="selectContactsFunc" action="{!selectContacts}" name="apex_selectContacts" rerender="pbMostRecentActivities" status="ajaxStatus"/>
 
   </apex:form>
  </apex:column>
  
...more columns...
  
 </apex:pageBlockList>


<apex:pageBlock title="Most Recent Activities" id="pbMostRecentActivities" >

 <apex:pageBlockList value="{!MostRecentActivities}" var="a" id="pblMostRecentActivities" >
  
... columns...
 
 </apex:pageBlockList>
 
</apex:pageBlock>

 





hpPMPhpPMP
I've similar problem where I'm trying to implement a listview for CampaignMember.

Any suggested solution?

If CampaignMember was first-class object, I won't have to worry about this implementation.
ShamilShamil
surjendu,

Can you please post your solution, I have a very similar issue.


Thanks,
shamil
knicholsknichols
Could you show all of the solution for this?  I just hit the same problem and found this post.
LegerdemainLegerdemain
See: http://wiki.apexdevnet.com/index.php/Wrapper_Class
Tiwari_ShwetaTiwari_Shweta

Hi Jason,

 

I am working on the functionality of checkbox in datatable. On clicking the checkbox,I have to retrive the value of corresponding row.I have aceive this functionality by using wrapper class.

Is this possible to acieve the functionality without using wrapper class.

 

Can you please help.

This was selected as the best answer
kitsunebravekitsunebrave
Hi,

Regarding this issue. I am trying to perform this logic to refresh a checkbox based on specific selected filter values.

I am waiting from anyone to answer this question regardless the @kmccoll and @TehNrd. How to avoid this issue basically to have a Specific Salesforce Record based on the selection of the Product Checkbox.

Please, follwing is the related business scenario for this issue:

I have two table primary and secondary. I want to retrieve the Product Info from primary table and show from secondary table. The Wrapper logic is completed, however, I need to display multiple selection based on one or more Products. Here is the Partial visualforce page and the apex method.
 
<table width="100%" border="2">
  <tr>
      <td width="75" valign="top" ><b>Search by Product</b>
           <div style="overflow:auto; height:250px;">
              <apex:pageBlockTable title="Search by Product Table" value={!ProductFilters}" var="productrecord" id="productsList">
                  <apex:column style="width:25px" >
                     <apex:inputCheckbox id="productLine1" onclick="showContent(this)" value="{!productrecord.selectedProduct}" />
                   </apex:column>
                   <apex:column style="width:50px" onclick="uncheckOther('productLine1')" value="{!productrecord.filter.Entitlement}" >
                   </apex:column>
               </apex:pageBlockTable>
            </div>
         </td>
    </tr>
</table>
<table width="100%" border="2" id="splitTable">
   <tr>
       <td width="100%" valign="top">
          <div id="content" style="overflow:auto; height:400px; display: block">
               <apex:pageBlockTable title="Results of the selection of Version/Entitlement Products on the initial page" value="{!displayItems}" var="record" id="displayListing">
                   <apex:column style="width:25px" >
                       <apex:facet name="header">
                         <apex:inputCheckbox id="displayChkBx" onclick="checkAll('productLine1','{!$Component.displayListing}', 'displayItemsLine1')" />
                       </apex:facet>
                         <apex:inputCheckbox value="{!record.selected}" id="selectLine1" />
                    </apex:column>
                    <apex:column id="colVersion" style="width:60px" value="{!record.dispItem.ProductVersion}" headerValue="Release Version">
                    </apex:column>
               </apex:pageBlockTable>
             </div>
          </td>
     </tr>
</table>

Apex method:
 
// Multi-select filter options

	public void filterBySelections()
	{
		selectionItemsListing.SetSelectedItemsList(collectSelectedProducts(), 
			collectSelectedVersions(), 
			collectSelectedComponents(), 
			collectSelectedBacklogs());
			
	}

 public Set<String> collectSelectedProducts()
    {
    	Set<String> allProducts = new Set<String>();
        this.selectedProductFilters.clear();
        for(productFilterWrapper productWrapper : this.productFiltersList)
        {
            if(productWrapper.selectedProduct == true)
            {
	        	System.debug('Product selected: ' + productWrapper.filter.Entitlement);
        		allProducts.add(productWrapper.filter.Entitlement);
            	this.selectedProductFilters.add(productWrapper.filter);
            }
        }
        return allProducts;
    }

Any ideas to complet this issue.

Thanks in advance.