Nivedita
Mega Expert

Hello Everyone,
I'm writing this article with an intention to help people who may come across akin kind of requirement in future.
Use case - I had a checkbox field on the form of (table hardware asset) which should be true if the attached file has any pdf file and the checkbox field should be false if the form doesn't have any pdf file attached.
There is a number of ways to do this. I have chosen business rules.
So there is 3 business rule for insertion of the new record, updating of existing record and for deletion of an attachment.

1) For inserting new record and considering above mentioned use case:
Table - Hardware, When to run -Before and  operation -insert

var almHW = new GlideAggregate('sys_attachment');
almHW.addQuery('table_name', 'alm_hardware');
almHW.addQuery('table_sys_id', current.sys_id);
almHW.addQuery('content_type','application/pdf');
almHW.addAggregate('COUNT');
almHW.query();
while (almHW.next()) {
if (almHW.getAggregate('COUNT').toString() > 0) {
current.(your checkbox field) = true;

}
}

 

2) For Updating the existing record
Table -Attachment, When to run -Before and  operation -insert and update
var file = current.getValue('file_name');
if(file.indexOf('pdf')!= -1 ){
var almHw = new GlideRecord('alm_hardware');
almHw.addQuery('sys_id', current.table_sys_id);
almHw.query();
if (almHw.next()) {
almHw.(your checkbox field) = true;
almHw.update();
}}

3) For deleting pdf file

Table -Attachment, When to run -After and  operation -Delete

var almHW = new GlideAggregate('sys_attachment');
almHW.addQuery('table_name', 'alm_hardware');
almHW.addQuery('table_sys_id', current.table_sys_id);
almHW.addQuery('content_type', 'application/pdf');
almHW.addAggregate('COUNT');
almHW.query();
while (almHW.next()) {

if (almHW.getAggregate('COUNT').toString() == 0) {

var hardwareTable = new GlideRecord('alm_hardware');
hardwareTable.addQuery('sys_id', current.table_sys_id);
hardwareTable.query();
if (hardwareTable.next()) {

hardwareTable.(your checkbox field)= false;
hardwareTable.update();
}

}

Hope it helps.
Thanks!!

Version history
Last update:
‎07-09-2021 11:29 AM
Updated by: