Attachment mandatory is not working fine on onchange client script

Srinivas K
Tera Contributor

Hi All,

For making attachment mandatory in onchange client script

Below is the script written

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var t= g_form.getValue('type');
if (t== 'Document') {
var attachment = new GlideRecord('sys_attachment');
attachment.addQuery('table_name', 'change_request');
attachment.addQuery('table_sys_id', g_form.getUniqueValue());
attachment.query();
if (!attachment.next()) {
alert("Please include attachment");
return false;
}
}

}

 

It is working when I select the choice option as document, an alert is appearing

But when I close the alert and clicking on saving, then the record is getting saved, but it should not happen.

 

Attachment should be still shown as  mandatory if nothing is selected.

 

@Ankur Bawiskar  pl guide

12 REPLIES 12

Brad Bowman
Kilo Patron
Kilo Patron

As an onChange script, this is doing what it should, even though GlideRecords are unsupported and not best practice in a client script.  Return false in an onChange script is pointless as there is nothing to abort/prevent.  So you could have this script, or a best practice one that calls a Script Include via Glide Ajax, to alert the user that an attachment is required when the Type changes, but then you would also need a similar onSubmit client script (it can call the same SI the same way as onChange) to return false after the alert that would prevent the form submission / update.  Another way to do this is in the onChange script after the alert, clear the value of a mandatory field so that the form can't be submitted until that field is populated again, then you would want to make sure that the onChange script triggers on that field change. 

Anurag Tripathi
Mega Patron
Mega Patron

Add the same to an onsubmit client script.

Also it is not advisable to have GlideRecord query in a Client script.

 

-Anurag

Anoja
Mega Sage

Hi,

This video helps to fulfill your requirement.

https://www.youtube.com/watch?v=mBCuGw2GhpE&list=PLKEMwVOiw5gjfZZMBPEfGTP-VpiM2zoAc&index=18

 

Thanks,

Anoja

Ankur Bawiskar
Tera Patron
Tera Patron

@Srinivas K 

this is for normal form or catalog form?

Regards,
Ankur
✨ Certified Technical Architect  ||  ✨ 9x ServiceNow MVP  ||  ✨ ServiceNow Community Leader