+ Start a Discussion
abivenkatabivenkat 

Checkbox column in pageBlockTable - Functionality

 

hi all,

 

i have a pageBlockTable in my VF page. 1st Column is a checkbox column and 2nd column is a column which changes dynamically based on the user's selection, let's say for example, 2nd Column is a "Name" retrieved from the account object. Now if the user checks the checkbox, i have to read the value of the checkbox and if it is checked, then i have to retrieve the value associated with the checked checkbox.

 

what i should do to relate the Name column with the check box column?? please help me to achieve this functionality..

 

 

Thanks,

abivenkat,
SFDC Learner 

Devendra@SFDCDevendra@SFDC

 

Hi abivenkat,

 

I think, you will have to use Wrapper Class functionality here.

 

Please refer to the below link:

 

http://wiki.developerforce.com/page/Wrapper_Class

 

Hope this helps.

 

Thanks,

Devendra

Navatar_DbSupNavatar_DbSup

Hi,

 

You can use the below code snippets as reference .In the below code contact id will display when the check box will checked.

 

-----------  VF Page--------------

<apex:page tabStyle="Task" sidebar="false" showHeader="false" id="page1" controller="clsSearchContact">
<apex:form >
<script>
var flag=0;
var SelectConId1='';
function checkAll(cb)
{    
    flag=0;
    SelectConId1='';
    var inputElem = document.getElementsByTagName("input");
    for(var i=1; i<inputElem.length; i++)
    {
        if(inputElem[i].id.indexOf("checkedone")!=-1)
        {
            inputElem[i].checked = cb.checked;
            flag=flag+1;
            SelectConId1=SelectConId1+inputElem[i].name+',';
        }
    }
    if(cb.checked!=true)
    {
        SelectConId1="";
        flag=0;
    } 
    alert(SelectConId1);
  
}

function checkone(cb)
{
    var countchbox=0;
   
    if(cb.checked)
    {   
        flag=flag+1;
        if((SelectConId1.length)<=1)
        {
            SelectConId1=cb.name+',';
        }
        else
        {
            SelectConId1=SelectConId1+cb.name+',';
        }
    }
    else if((cb.checked)!=true)
    {
        flag=flag-1;
        if((SelectConId1.length)<=1)
        {
            SelectConId1=cb.name+',';
        }
        else
        {
            var allids=SelectConId1.split(',');
            var idarray='';
            for(var i=0;i<allids.length;i++)
            {
                if(allids[i]!=cb.name  && allids[i]!='')
                {
                    idarray=idarray+allids[i]+',';
                }
            }
            SelectConId1=idarray;
        }
    }
    
     var inputElem = document.getElementsByTagName("input");
    for(var i=0; i<inputElem.length; i++)
    {
        if(inputElem[i].id.indexOf("checkedone"))
        {
            countchbox=countchbox+1;
        }
    }
    if(flag==countchbox-1)
    {
          document.getElementById("main").checked=true;
    }
    else
    {
         document.getElementById("main").checked=false;
    }
   alert(SelectConId1);
}

function search_element()
{
    //alert('hello');
    var element=document.getElementById("searchtext").value;
   // alert(element);
    searchelement(element);
    return false;
}
function addtolist()
{
   
    if((SelectConId1.length)<=1)
    {
        alert('Please select atleast one contact');
        return false;
    }
    else
    {
        addtolistcontact();
    }
}

function addtolistcontact()
{
   
       // var value1=window.parent.opener.document.getElementById("selectedcontactid").value;
       // if(value1.length<=0)
        {
       //     window.parent.opener.document.getElementById("selectedcontactid").value=SelectConId1;
        }
       // else
        {
       //     value1=value1+ SelectConId1;
       //     window.parent.opener.document.getElementById("selectedcontactid").value=value1;
        } 
       // window.parent.opener.document.getElementById("selectedcontactid").onchange();
       // return false;
    
}










function closethis()
{
    //addtolistcontact();
    //window.parent.close();
   //  return false;
}
</script>


    <apex:pageblock tabstyle="account">
     <apex:pageBlockSection title="Select Multiple Contact"   collapsible="false" columns="1">
     <Apex:pageBlock >
            
            <apex:pageBlockButtons location="both" >
            <apex:outputLabel >&nbsp;</apex:outputLabel>
                <apex:commandButton onclick="return addtolist();" value="Add to List"/>
                <Apex:commandButton value="Done"  onclick="return closethis()"/>
            </apex:pageBlockButtons>
            <apex:outputPanel >
                <input type="text" id="searchtext"/>
                <apex:actionFunction immediate="true"  action="{!searchcontact}" reRender="pbtable" name="searchelement">
                    <apex:param name="assignserach" value="" assignTo="{!searchfiled}"/>
                </apex:actionFunction>
                <apex:commandButton value="search" onclick="return search_element();" />
            </apex:outputPanel>
            <apex:pageBlockTable value="{!getconlist}" var="cc" id="pbtable">
                <apex:column >
                    <apex:facet name="header"> 
                        <input type="checkbox" id="main" onclick="return checkAll(this)"  /> 
                        
                    </apex:facet>
                     <input type="checkbox" name="{!cc.id}" id="checkedone"  onclick="return checkone(this)"  /> 
                    </apex:column>
                <div id="{!cc.id}">
                <apex:column >
                    <apex:facet name="header" >Name</apex:facet>
                    {!cc.name}
                        </apex:column>
                <apex:column >
                    <apex:facet name="header" >Title</apex:facet>
                    {!cc.Title}
                </apex:column>

                  <apex:column >
                     <apex:facet name="header" >Phone</apex:facet>
                    {!cc.phone}
                </apex:column>
                  <apex:column >
                    <apex:facet name="header" >Email</apex:facet>
                    {!cc.email}
                </apex:column>

                <apex:column >
                    <apex:facet name="header" >Account/Company</apex:facet>
                    {!cc.account.name}
                </apex:column>
                
                <apex:column >
                    <apex:facet name="header" >Owner</apex:facet>
                    {!cc.owner.name}
                </apex:column>
                </div>
            </apex:pageBlockTable>
      
        
       </Apex:pageBlock>
       </apex:pageBlockSection>
    </apex:pageblock>
    </apex:form>
</apex:page>








----------  Apex Controller ---------------

public class clsSearchContact
{
public string searchfiled{get;set;}
public list<contact> getconlist{get;set;}

public clsSearchContact()
{
    getconlist =new list<contact>();
    getconlist=database.query('Select name,phone,email,account.name,title,owner.name from contact limit 10');
}

public void searchcontact()
    {
         try
         {
         system.debug('@@@@@@@@searchfiled'+searchfiled);
         
           searchfiled= '%'+searchfiled+ '%';
             getconlist =new list<contact>();
             getconlist=database.query('Select name,phone,email,account.name,title,owner.name from contact  WHERE Name like :searchfiled limit 100');
           
         }
         catch(Exception e)
         {
             system.debug('Error'+e);
         }
    }
}

 Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved. 

Sagar Nagvekar 14Sagar Nagvekar 14
<!--
  This VF page will list tasks owned by a user in list view. Checking checkboxes on left hand side of tasks will
  assign those tasks to current user after he clicks on "Change ownership to me".
  Thus this will function like a queue for tasks. Any user can take ownership of any task.
-->
<apex:page controller="TestTakeOwnership">
  <apex:form >
    <apex:pageMessages />
    <script>
      var flag=0;
      var SelectConId1='';
      
      // for success message show from javascript itself
      var flag2 = 0;

      // total count of checkboxes visible
      var countchbox=0;

      function checkAll(cb)
      {
         //alert('All checkboxes have been checked or unchecked');
         flag=0;

         // List of IDs of the tasks. Comma separated.
         SelectConId1='';

         var inputElem = document.getElementsByTagName("input");

         for(var i=1; i<inputElem.length; i++)
         {
            if(inputElem[i].id.indexOf("checkedone")!=-1)
            {
               inputElem[i].checked = cb.checked;
               flag=flag+1;
               SelectConId1=SelectConId1+inputElem[i].name+',';
            }
         }
         //alert('Check all main checkbox checked. flag value is ' + flag);
         
         if(cb.checked!=true)
         {
            //alert('main checkbox is unchecked');
            SelectConId1="";
            flag=0;
         }
         //alert(SelectConId1);
      } 
      
      function checkone(cb)
      {
          //alert('One checkbox is checked or unchecked');      
          countchbox=0;
    
          if(cb.checked)
          {  
              flag=flag+1;
              //alert('now flag is ' + flag);
              //alert('now SelectConId1.length is ' + SelectConId1.length);
              
              if((SelectConId1.length)<=1)
              {
                  SelectConId1=cb.name+',';
              }
              else
              {
                  SelectConId1=SelectConId1+cb.name+',';                  
              }
          }
          else if((cb.checked)!=true)
          {
              //alert('cb.checked is false');
              flag=flag-1;
              //alert('checkbox unchecked, after decrementing flag value is ' + flag);
              if((SelectConId1.length)<=1)
              {
                  SelectConId1=cb.name+',';
              }
              else
              {
                  var allids=SelectConId1.split(',');
                  var idarray='';
                  for(var i=0;i<allids.length;i++)
                  {
                      if(allids[i]!=cb.name  && allids[i]!='')
                      {
                          //alert('this id wont be removed');
                          idarray=idarray+allids[i]+',';
                      }
                      else
                      {
                          //alert('removing this id as match found');
                          if(allids[i] == cb.name)
                          {
                              //alert('Removing this id as match found');
                          }
                          
                          if(allids[i] == '')
                          {
                              //alert('removing blank');
                          }
                          
                      }
                  }
                  SelectConId1=idarray;
              }
          }
          var inputElem = document.getElementsByTagName("input");
          
          for(var i=0; i<inputElem.length; i++)
          {
              if(inputElem[i].id.indexOf("checkedone")!=-1)
              {
                  // Counting total number of checkboxes  
                  countchbox=countchbox+1;                               
              }
          }
          //alert('Total number of checkboxes countchbox is ' + countchbox);
          //alert('flag value is ' + flag);            
          if(flag==countchbox)
          {
              //alert('flag is equal to countchbox');
              document.getElementById("main").checked=true;
              //alert('last checkbox is checked, so checkAll auto check doing');
          }
          else
          {
              //alert('flag is not equal to countchbox');
              document.getElementById("main").checked=false;
              //alert('last checkbox is not checked, so checkAll uncheck');
          }
          //alert(SelectConId1);
      }
      
      function chngeOwner()
      {
          //alert('chngeOwner called');
          if((SelectConId1.length)<=1)
          {
              alert('Please select at least one task to change its ownership to you');
          }
          else
          {
              //alert('Some task has been selected, so proceeding, SelectConId1 is ' + SelectConId1);
              // for success message show from javascript itself
              flag2 = flag;
              
              //alert('some ownership changing, so making flag 0, counting begin again');
              flag = 0;
          
              if(flag2 == 1)
              {
                  alert(flag2 + ' task will be assigned to you.');
              }
              else
              {
                  alert(flag2 + ' tasks will be assigned to you.');
              }
          
              paraFunction(SelectConId1); 
          }      
          // Reset the counter
          SelectConId1 = '';
      }
    </script>
    
    <apex:outputPanel id="displayCountPanel1">
      Total number of tasks in this queue: <apex:outputLabel value="{!totalCount}"/>
    </apex:outputPanel>
    <br/>    
    <!--
      chngeOwner() is the javascript function
    -->
    <apex:commandButton value="Change ownership to me" onclick="chngeOwner()" reRender="outputTable, displayCountPanel1" status="counterStatus"/>
    <apex:actionStatus startText=" (Processing...)" stopText="" id="counterStatus"/>
    <br/> <br/>    
    <apex:outputPanel >
      Select the checkboxes below for the tasks you would like to take ownership of and then click on the button "Change ownership to me"
    </apex:outputPanel>

    <apex:pageBlock id="outputTable">
      <apex:pageBlockTable value="{!tasksOwnedByQueue}" var="t">
        <apex:column >
          <apex:facet name="header">
            <!--
              This adds the checkbox on each row of the table of tasks
            -->
            <input type="checkbox" id="main" onclick="return checkAll(this)"/>
          </apex:facet>
          <input type="checkbox" name="{!t.id}" id="checkedone" onclick="return checkone(this)"/>
        </apex:column>
      
        <div id="{!t.id}">
          <apex:column headerValue="Task ID" value="{!t.id}"/>
          <apex:column headerValue="Subject" value="{!t.subject}"/>
          <apex:column headerValue="Related to" value="{!t.whatid}"/>
          <apex:column headerValue="Related to name" value="{!t.whoid}"/>
          <apex:column headerValue="Status" value="{!t.status}"/>
        </div>
      </apex:pageBlockTable>
      Total number of tasks in this queue: <apex:outputLabel value="{!totalCount}"/>
    </apex:pageBlock>
    
    <!--
      changeOwnership() is the function in the controller class :- TestTakeOwnership
    -->
    <apex:actionFunction name="paraFunction" action="{!changeOwnership}" reRender="outputTable, displayCountPanel1">    
      <apex:param id="anode" name="node" value="" />
    </apex:actionFunction>
  </apex:form>
</apex:page>

// The controller class
public class TestTakeOwnership
{
    private list<task> tasksOwnedByQueue = new list<task>();
    public integer totalCount {get;set;}
    User u;
   
    public TestTakeOwnership()
    {
        u = [select id, name from user where name = 'John Connor'];
        tasksOwnedByQueue = [select id, subject, status, whatid, whoid from task where ownerid = :u.id and status != 'Completed'];
        totalCount = tasksOwnedByQueue.size();
        System.debug('//////////////////constructor code executes - total number of tasks is ' + totalCount);    
    }
    
    public list<task> getTasksOwnedByQueue()
    {
        return tasksOwnedByQueue;
    }
    
    public void changeOwnership()
    { 
        String para = Apexpages.currentPage().getParameters().get('node');
        System.debug('======================= ' + para);
        list<id> changeOwnershipOfTheseTasks = para.split(',');
        System.debug('////////////////////list of tasks is ' + changeOwnershipOfTheseTasks);
        System.debug('////////////////////Number of tasks identified is ' + changeOwnershipOfTheseTasks.size());
        list<task> modifyTasks = [select id, subject from Task where id in :changeOwnershipOfTheseTasks];
        totalCount = tasksOwnedByQueue.size();
        System.debug('//////////////////before changing ownership :- total number of tasks in queue is ' + totalCount);
        
        try
        {
            System.debug('////////////////Current user id is - ' + UserInfo.getUserId());
            String currentUserId = UserInfo.getUserId();
            
            for(Task modifyOwner : modifyTasks)
            {
                modifyOwner.ownerid = currentUserId;
            }
            update modifyTasks;
            
        }
        catch(Exception e)
        {
            Apexpages.addMessage( new ApexPages.Message (ApexPages.Severity.ERROR, 'Error Message'));
        }
        tasksOwnedByQueue = [select id, subject, status, whatid, whoid from task where ownerid = :u.id and status != 'Completed'];
        totalCount = tasksOwnedByQueue.size();
        System.debug('//////////////////after changing ownership :- total number of tasks in queue is ' + totalCount);
    }       
}
vijayskvijaysk
Hi ,

I have a requirements as below using checkbox functionality:-
*i need to search list of products based on search string(this i have completed)
*I need to make multiply of field1,field2(this i have completed) and render it in  "total" as apex:variable
*i need to calculate sum of "total" field values in last column(This is completed)level field values and show in "Grand Total"
*I need to show the checkbox functionality of each searched record of products(this is completed)

For below requirement when i use wrapper class to get the selected list of products,  i am unable to get to grand total due to listRecord getting size as "0"
*I need to insert the list of product records selected into custom object.
User-added image

Below is the vf,apex class

Vf:-
--
<apex:page controller="ProductDtlsController" sidebar="false">
    <script type="text/javascript">
    function selectAllCheckboxes(obj,receivedInputID){
        var inputCheckBox = document.getElementsByTagName("input");
        for(var i=0; i<inputCheckBox.length; i++){
            if(inputCheckBox[i].id.indexOf(receivedInputID)!=-1){
                inputCheckBox[i].checked = obj.checked;
            }
       }
    }
    </script>
    <apex:form id="frm">       
        <apex:pageBlock >
            <apex:pageBlockButtons location="bottom">
                <apex:commandButton value="Search" action="{!searchprts}" reRender="product-table" />
                <apex:commandButton value="Save"  />
            </apex:pageBlockButtons>
            <apex:pageBlockSection id="product-table" columns="1">
                <apex:pageBlockSectionItem >
                    <apex:outputLabel value="Name" />
                    <apex:inputText value="{!name}" />
                </apex:pageBlockSectionItem>
                <apex:pageBlockTable value="{!Products}" var="prdlst">
                    <apex:column >
                        <apex:facet name="header">
                            <apex:inputCheckbox id="chkbox" onclick="selectAllCheckboxes(this,'inputId')"/>
                        </apex:facet>
                        <apex:inputCheckbox id="inputId" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">Name</apex:facet>
                        <apex:outputText id="name" value="{!prdlst.Name}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">Product Price Unit </apex:facet>
                        <apex:outputText id="id1" value="{!prdlst.Product_Price_Unit__c}" />
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">Quantity</apex:facet>
                        <apex:inputField id="id2" value="{!prdlst.Quantity__c}" >
                            <apex:actionSupport event="onchange" action="{!onFieldChange}" reRender="frm"/>
                        </apex:inputField>
                    </apex:column>
                    <apex:column >
                        <apex:facet name="header">Total </apex:facet>
                        <apex:variable var="totalPrice" value="{!prdlst.Product_Price_Unit__c*prdlst.Quantity__c}" />
                        <apex:outputText value="{!totalPrice}" />
                    </apex:column>
                </apex:pageBlockTable>
                <apex:outputLabel >Grand Total =
                    <apex:outputText value="{!GrandTotal}" id="value"/>
                </apex:outputLabel>
            </apex:pageBlockSection>
        </apex:pageBlock>
    </apex:form>
</apex:page>

Apex:-
---
public class ProductDtlsController {
    public List<Product2> Products { get; set; }
    public String name { get; set; }
    public decimal totalPrice{get;set;} 
    public decimal GrandTotal {get; set;}
    
    
    public ProductDtlsController()
    {
        Products = new List<Product2>();
        GrandTotal=0;
    }
    public void searchprts()
    {
       String srchSyl = '%'+name+'%';
       
       Products  = [select Id,Name,Quantity__c,Product_Price_Unit__c from Product2 where Name like : srchSyl];
    }
    
    public Integer onFieldChange(){
        decimal total = 0;
        for(integer i=0;i<Products.size();i++){
           
            total = total+(Products[i].Product_Price_Unit__c*Products[i].Quantity__c);
        }
        GrandTotal = total;
        return null;
    }
    public void processSelected(){
        
    }
    public class wrapAccount {
        public Account acc {get; set;}
        public Boolean selected {get; set;}
 
        public wrapAccount(Account a) {
            acc = a;
            selected = false;
        }
    }
}

When i try to do below sample using wrapper class for selected products to insert into custom object, i am not getting the grand total.
---------------------------------------
  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;
        }
    }
-------------------------------
Any help would be highly appreciated ?