listener to control two exclusive checkboxes

  • 1
  • Question
  • Updated 5 years ago
I have an object with two checkbox fields (Primary and Secondary). For any record the checkboxes are exclusive - one or the either checkbox can be checked, or neither can be checked. I've got a Table of such records.

How might I create a listener (event handler & renderer) that would enforce exclusivity? I created a listener that would force Secondary to be unchecked whenever Primary is checked, but I need the opposite to also be enforced. I've tried separate listeners on the two fields, but I can't get both to work at the same time, and if they did I'd end up with dueling listeners.

If I had complete control over the object, I'd replace the checkboxes with a picklist and display it as radio buttons, but I don't.

Here's my one-way listener, for what it's worth:


var field = arguments[0],
value = arguments[1],
renderer = skuid.ui.fieldRenderers[field.metadata.displaytype],
mode = field.mode;
// Get the household members model we are using for the renderer
var householdMembersModel = skuid.model.getModel('NewHouseholdMember');
if (mode == 'edit') {
// Specify that we want to display our field as a checkbox
field.options.type = 'BOOLEAN';
}
// Run standard renderer for the current mode (applies to read/edit mode)
renderer[mode](field,value);
// Function that will update the value of our HouseholdMember row's Secondary field
// based on the Primary field (can't check both)
var updatePrimaryField = function(){
// Find the selected HouseholdMember
var newEntryId = field.model.getFieldValue(field.row,'Id');
// Find the corresponding HouseholdMember record
var entry = householdMembersModel.getRowById(newEntryId);
var newSecondary = householdMembersModel.getFieldValue(entry,'households__IsSecondary__c');
var newPrimary = householdMembersModel.getFieldValue(entry,'households__IsPrimary__c');

alert("Primary Renderer: Primary = " + newPrimary + "\nSecondary = " + newSecondary);

// Force Secondary field to unchecked if Primary was checked
if(newPrimary) field.model.updateRow(field.row,'households__IsSecondary__c',false);
// Rerender the Secondary field in the row, if that field has been rendered.
var item = field.editor.lists[0].renderedItems[field.row.Id];
if (item) {
$j.each(item.fields,function(i,f){
if (f.id == 'households__IsSecondary__c') {
f.render();
return false;
}
});
}
};
if (mode == 'edit') {
// If we do not yet have a value for our Primary field, update it.
// if (!field.model.getFieldValue(field.row,'households__IsPrimary__c')) {
// updatePrimaryField();
// }
// Attach an event handler to our field's <input> checkbox element
var input = field.element.find('input');
input.on('change',function(){
updatePrimaryField();
});
}
Photo of Ken Neff

Ken Neff

  • 408 Points 250 badge 2x thumb

Posted 5 years ago

  • 1

Be the first to post a reply!