Reputation: 1203
I have a tab, containing a section which a large number (20+) of fields occupy. They are all checkboxes, one of which is a "N/A" choice. Can anyone suggest a simple way of writing javascript that will ensure at least one choice is made, or if not, only let the user continue past this section if N/A is ticked. I'm trying to avoid checking the value in each and every checkbox. Any suggestions?
Thanks
Upvotes: 0
Views: 223
Reputation: 17552
I think this is just a case of using some of the existing functions in the Xrm.Page object, there are a couple for working with lots of attributes at once. Regardless of how you do it you will have to check every field, but you can do it in quite a succinct way.
I would suggesting adding an OnSave event, with code that does something like this:
//we want to make sure that at least one of these is populated
//new_na is the na field
//the others are the possible choices
var requiredFields = ["new_na", "new_field1", "new_field2", "new_field3"];
//this loops through every attribute on the page
Xrm.Page.data.entity.attributes.forEach(function (attribute, index) {
//this will track if at least one field was set
bool atLeastOneSet = false;
//see if the requiredFields array contains this field
if (requiredFields.indexOf(attribute.getName()) != -1) {
//if it is required, check the value
if(attribute.getValue()) {
//if it set update the bool flag
atLeastOneSet = true;
}
}
//finished processing all fields, if atLeastOneSet is false no field has been set
if(!atLeastOneSet) {
//If this code is used in an on save event this will prevent the save
Xrm.Page.context.getEventArgs().preventDefault();
//Give the user some message
alert("At least one field must be populated");
}
});
Untested code, but should hopefully give you a good idea of how to progress.
Upvotes: 1
Reputation: 4111
From a user interface standpoint, you could split that section into two sections (without header label so it looks like one section). The first would have the N/A checkbox, and if checked the Javascript would simply hide the section with all the other checkboxes.
If you actually want to check values, you should still be able to use the same concept, but use jQuery to find all checkboxes in that section with all the normal checkboxes. If none of them are checked, you could stop a Save with an error message if N/A is also not checked.
Upvotes: 1