SuiteScript 2.0 TypeError Cannot call method "getValue" of undefined

Viewed 1403

I'm trying to get the values from two transaction body field using this code below .

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 *@param {Record} context.currentRecord
 */

define(['N/record'], 
function (msg) {
    
    function beforeSubmit(context) {
      try {

        var record = context.currentRecord;               

        var createdDate = record.getValue({
            fieldId: 'createddate'
        });

        var dataNecessidade = record.getValue({
            fieldId: 'custbodyek_data_nece_requ_po'
            
        });

        console.log(createdDate ,dataNecessidade);        

        }
        catch(ex){
        log.error(ex);
        }
    }
    return {
        beforeSubmit : beforeSubmit,
    
    };
});

The error raised is "TypeError: Cannot call method "getValue" of undefined"

What I'm doing wrong here?

Thank you!

3 Answers

There is no currentRecord property on the context passed into a user event, hence the error message telling you that record is undefined. Review the docs for the beforeSubmit entry point to find the appropriate values.

You try to write it like this, I always use this method to get the field value.

const bfRecord= context.newRecord;
const createdDate = bfRecord.getValue('createddate');

On SuiteScript 2 each entry point has different parameters so you need to check those parameters on the Help or if you use an IDE like Eclipse, you will get that information when you create a new script, so for a UserEvent script and the beforeSubmit entry point, you will get something like this:

/**
 * Function definition to be triggered before record is loaded.
 * 
 * Task #5060 : calculate PO Spent Amount and Balance in realtime
 *
 * @param {Object} scriptContext
 * @param {Record} scriptContext.newRecord - New record
 * @param {Record} scriptContext.oldRecord - Old record
 * @param {string} scriptContext.type - Trigger type
 * @Since 2015.2
 */

and then you can see that the context parameter doesn't have a currentRecord property, instead, it has two other parameters that you can use newRecord or oldRecord so your code can be like this:

/**
 *@NApiVersion 2.x
 *@NScriptType UserEventScript
 *@param {Record} context.currentRecord
 */

define(['N/record'], 
function (msg) {
    // are you aware that you are "injecting" the 'N/record' library into the 'msg' variable ???
    function beforeSubmit(context) {
      try {

        var record = context.newRecord;               

        var createdDate = record.getValue({
            fieldId: 'createddate'
        });

        var dataNecessidade = record.getValue({
            fieldId: 'custbodyek_data_nece_requ_po'
            
        });

        console.log(createdDate ,dataNecessidade);        

        }
        catch(ex){
        log.error(ex);
        }
    }
    return {
        beforeSubmit : beforeSubmit,
    
    };
});
Related