How to get number of attachments for a catalog item in client script on submit
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-21-2024 01:05 AM
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
02-21-2024 01:31 AM
Hi @Anandini
In ServiceNow, getting the number of attachments associated with a catalog item via a client script is a multi-step process. ServiceNow’s client scripts run on the client’s browser, and to get the attachments count, you need to interact with the server because attachment data is stored on the server side. Here is how you can do it using an onSubmit client script:
1. First, you need to create a Script Include that will handle the server-side logic of counting attachments.
var AttachmentUtils = Class.create();
AttachmentUtils.prototype = {
initialize: function() {
},
getAttachmentCount: function(sysId) {
var attachment = new GlideRecord(‘sys_attachment’);
attachment.addQuery(‘table_sys_id’, sysId);
attachment.query();
var count = 0;
while (attachment.next()) {
count++;
}
return count;
},
type: ‘AttachmentUtils’
};
2. Then, in your client script, you will need to use an onSubmit script to call the server-side code, which will count the number of attachments.
var sysId = g_form.getUniqueValue();
// Call the server from the client script using GlideAjax
var ga = new GlideAjax(‘AttachmentUtils’);
ga.addParam(‘sysparm_name’, ‘getAttachmentCount’);
ga.addParam(‘sysparm_sys_id’, sysId);
// This callback function will process the asynchronous GlideAjax response
ga.getXMLAnswer(function(answer) {
var attachmentCount = parseInt(answer, 10);
if (attachmentCount == 0) {
// Handle your validation if there are no attachments
g_form.addErrorMessage(“Please add an attachment before submitting.”);
g_form.preventDefault(); // prevent the form from being submitted
}
// If there are attachments, the form will be submitted normally
});
}
Please mark this as helpful and Accepted, if this solves your query
Thanks & Regards
Deepak Sharma