Creating a Client script that is triggered via a HTML button in a record producer.

LePhucTanT
Giga Expert

Hi Community,

After successfully creating a HTML button via a variable in a record producer, now I need to make add functionality to it. I have a snippet of the script below : 

function onLoad() {
// Access the HTML button with the ID set in the HTML variable
var button = document.getElementById('validateButton');

if (button) {
// Attach click event to trigger file name validation for attachments
button.addEventListener('click', function() {
validateAttachments(); // Call the validation function for attachments
});
}
}

// Validate attachments and their file names
function validateAttachments() {
var attachmentValid = true;
var validPattern = /^[a-zA-Z0-9_\-]+\.[a-zA0-9]+$/; // Regex pattern for validating file name

// Get the Sys ID of the current record (to check attachments for this record)
var recordSysId = g_form.getUniqueValue();

// Log the record Sys ID to check
console.log('Checking attachments for record with Sys ID: ' + recordSysId);

// Create a GlideRecord query to retrieve attachments related to the current record
var grAttachment = new GlideRecord('sys_attachment');
grAttachment.addQuery('table_sys_id', recordSysId); // Filter by the current record's Sys ID
grAttachment.query();

// Log how many attachments were found
console.log('Number of attachments found: ' + grAttachment.getRowCount());

// Loop through all the attachments and validate their names
var hasInvalidFile = false;
while (grAttachment.next()) {
var fileName = grAttachment.getValue('file_name'); // Get the file name of the attachment

// Log the file name to check
console.log('Validating file: ' + fileName);

// Check if the file name matches the pattern
if (!validPattern.test(fileName)) {
g_form.showFieldMsg('trigger_file_validation', 'Attachment "' + fileName + '" has an invalid name!', 'error');
attachmentValid = false; // Mark validation as failed
hasInvalidFile = true; // Flag indicating an invalid file
break; // Stop at the first invalid attachment
}
}

// If all attachments are valid, show a success message
if (!hasInvalidFile) {
g_form.clearMessages();
g_form.addInfoMessage('All attachments have valid names!');
}
}
Hoping this script would be able to pull the HTML out, add a listener event to know when it is clicked. and if its clicked it will run a file check via sys_attachment making sure it follows the correct file name. 

I have been attempting this but am unable to get a message pop up to check if the messages are working as intended or not. 

If anyone knows more about scripting or know what's the best way to action this function help would be appreciated. 

Regards

Tran
Thank you in advance.

0 REPLIES 0