Checkbox in DataTable

We have to use wrapper class for displaying the check box in a data table or page block table. I am providing sample code which creates new contact, save and delete selected contact records of respective Account.

Page:











































Apex Code:

 
public class CustomAccountController {

public Account acc{get;set;}
private Id AccId{get;set;}
public List contactList{get;set;}
public contact newCont{get;set;}

class ContactWrapper{
public Contact cont { get; set; }
public boolean isSelected{ get; set; }
ContactWrapper(Contact c) {
cont = c;
isSelected = false;
}
}



public CustomAccountController() {
try {
AccId = ApexPages.currentPage().getParameters().get('id');
if(AccId != null) {
acc = [select Name,Description,NumberOfEmployees,Phone,Website,Industry from Account where id = :AccId];
initContact(acc);
} else {
ApexPages.addmessage(new ApexPages.message(ApexPages.severity.Error, 'Please pass parameter to this page. For eg. /apex/CustomAccount?id=0019000000OKdsH'));
}
} catch(Exception e) {
apexPages.addMessages(e);
}
}

public void initContact(Account acc) {
if(acc != null) {
contactList = new List();
for(Contact c : [Select Id, FirstName, LastName, Email from Contact where AccountID =: acc.Id]) {
contactList.add(new ContactWrapper(c));
}
}
}
public pageReference save() {
try {
List contactToUpdate = new List();
for(ContactWrapper c: contactList) {
if(c.isSelected) {
contactToUpdate.add(c.cont);
}
}
update contactToUpdate;
} catch(Exception e) {
apexPages.addMessages(e);
}
return null;
}

public pageReference delet() {
try {
List contactToDelete = new List();
for(ContactWrapper c: contactList) {
if(c.isSelected) {
contactToDelete.add(c.cont);
}
}
delete contactToDelete;
initContact(acc);
} catch(Exception e) {
apexPages.addMessages(e);
}
return null;
}

public pageReference newContact() {
newCont = new Contact(AccountId = accId);
return null;
}

public pageReference saveNewContact() {
try {
upsert newCont;
newCont = null;
initContact(acc);
} catch(Exception e) {
apexPages.addMessages(e);
}
return null;
}
}

Feel free to write your comment or mail me at sandeep.saini482@gmail.com for any further query.

Published by Sandeep Kumar

He is a Salesforce Certified Application Architect having 11+ years of experience in Salesforce.

3 thoughts on “Checkbox in DataTable

Leave a reply to Sandeep Kumar Cancel reply