Page 1 of 1
Conditional Mandatory subform field
Posted: Tue Feb 25, 2020 2:35 am
by nc07
Hi,
I have a form that has two subforms. I want to make one of the fields conditional mandatory based on the selection in one of the fields in the main form. Before save i want to check if the value selected in the main form field is '3' for example then one of the fields in the subform must be filled otherwise it can be null.
the main form field id is po_categ, subform id is field04 and subform field id is co_actn
how can this be done either before save in PHP or javascript?
Re: Conditional Mandatory subform field
Posted: Tue Feb 25, 2020 7:38 am
by admin
Re: Conditional Mandatory subform field
Posted: Tue Feb 25, 2020 8:01 am
by kev1n
Here's how it can be done with Javascript. (The preferred way would be a server side check with PHP)
Code: Select all
function sumFormColArray(id, fieldname) {
var a = Array();
var sf = nuSubformObject(id);
var c = sf.fields.indexOf(fieldname);
for(var i = 0; i < sf.rows.length; i++) {
if(sf.deleted[i] == 0) {
var rv = sf.rows[i][c];
a.push(rv);
}
}
return a;
}
function subFormHasMissingValuesInColumn(id, fieldname) {
var arr = sumFormColArray(id, fieldname)
return arr.findIndex(e => e === "") > -1
}
function nuBeforeSave() {
if (nuFORM.edited === true) {
if ($('#po_categ').val() !== "") {
if (subFormHasMissingValuesInColumn('field04','co_actn')) {
nuMessage(["There are missing values in column xyz."]);
return false;
}
}
}
return true;
}
Re: Conditional Mandatory subform field
Posted: Tue Feb 25, 2020 7:03 pm
by kev1n
The PHP equivalent - to be added in the BS (Before Save) event:
Code: Select all
$id = 'field04'; // subform object id
$fieldname = 'co_actn'; // subform field name
if ("#po_categ#" !== "") {
if (blankValuesInSubformField($id, $fieldname) > 0) {
nuDisplayError('Field xyz '.nuTranslate('cannot be left blank'));
}
}
function blankValuesInSubformField($id, $fieldname) {
$sf = nuSubformObject($id);
$c = array_search($fieldname, $sf->fields);
for($i = 0 ; $i < count($sf->rows) ; $i++){
$value = $sf->rows[$i][$c];
$notDeleted = $sf->deleted[$i] == 0;
if ($notDeleted && $value == "") {
$r++;
}
}
return $r;
}
Re: Conditional Mandatory subform field
Posted: Tue Feb 25, 2020 10:47 pm
by nc07
Thank You, kev1n;
I have tried both the codes, JS & PHP, and both work fine.
Thank You so much for your time and help, really appreciated.
Cheers.
nc07
Re: Conditional Mandatory subform field
Posted: Wed Feb 26, 2020 7:37 am
by kev1n
You're welcome!