Usually, we are writing action of a Button that is added using User ever script with the help of a client script.
However, consider a case where we need to pass the data which is only available on the newRecord /oldRecord Object on the User event script to a custom page on a button click. This scenario can be handled by adding the Button action defining in the User event script. This method will also help us to eliminate the intermediate client script.
Find below sample
/**
* @NApiVersion 2.1
* @NScriptType UserEventScript
*/
define(['N/url', 'N/ui/serverWidget'],
(url, serverWidget) => {
/**
* Defines the function definition that is executed before record is loaded.
* @param {Object} scriptContext
* @param {Record} scriptContext.newRecord - New record
* @param {string} scriptContext.type - Trigger type; use values from the context.UserEventType enum
* @param {Form} scriptContext.form - Current form
* @param {ServletRequest} scriptContext.request - HTTP request information sent from the browser for a client action only.
* @since 2015.2
*/
const beforeLoad = (context) => {
try {
if (context.type == 'view') {
log.debug("start", "button");
var recId = context.newRecord.id;
var recType = context.newRecord.type;
//map to Suitelet
var suiteletURL = url.resolveScript({
scriptId: "customscript_jj_sl_taxinvoiceprint", //Script ID of Suitelet Page
deploymentId: "customdeploy_jj_sl_taxinvoiceprint", //Deployment ID of Suitelet Page
params: {
recId: recId,
recType: recType
}
});
//Add a custom Button on Record View
context.form.addButton({
id: 'custpage_tax_invoice_button',
label: 'Tax Invoice Print',
functionName: 'window.printTaxInvoice' //function triggered on button click
});
var virtualfieldID = context.form.addField({
id: 'custpage_virtual_field',
type: serverWidget.FieldType.INLINEHTML,
label: 'Print Tax Invoice'
});
virtualfieldID.defaultValue =`<script>window.printTaxInvoice=function(){ window.open("${suiteletURL}"); }</script>`;
}
} catch (e) {
log.debug({
title: e.name,
details: e.message
});
}
}
return { beforeLoad }
});