How to handle if my getValue('number').split(',').length; return NULL

Thomas Miles
Tera Contributor

find_real_file.png

I am writing a server script similar to this instead i have a List field that holds multiple items and I want to count how many items are in that list when the list is populated using 

problem_data.list_field = gr.getValue('list_field').split(',').length; works FINE , BUT when it is NULL i get an error 

Please help not sure how to get around an empty value

1 ACCEPTED SOLUTION

Marcin20
Mega Guru

Hi Thomas,

I propose the following: 

 

if ( !(gr.list_field.nil() ) {

     problem_data.list_field = gr.getValue('list_field').split(',').length; 

} else {

      problem_data.list_field = 0; 

}

 

Best Regards,

Marcin

 

If my answer helped you in any way, please mark this answer as helpful and correct.

 

View solution in original post

4 REPLIES 4

Marcin20
Mega Guru

Hi Thomas,

I propose the following: 

 

if ( !(gr.list_field.nil() ) {

     problem_data.list_field = gr.getValue('list_field').split(',').length; 

} else {

      problem_data.list_field = 0; 

}

 

Best Regards,

Marcin

 

If my answer helped you in any way, please mark this answer as helpful and correct.

 

Thank you so much this worked!

Yousaf
Giga Sage

Hi Thomas,

Try this  >  gr.getValue('list_field').split(',').length || ' ';

 

Mark Correct or Helpful if it helps.

Thanks,
Yousaf


***Mark Correct or Helpful if it helps.***

If that doesn't work 

Use this custom getValueAK function that also supports dot-walking.  Include this function in the script itself, or dump this into a Script Include:

 

// You can put this in a Script Include
// Features:
// - always returns a string
// - can dot-walk
// - returns empty string instead of null (for both empty fields and non-existent fields)
// - returns string 'true' or string 'false' for boolean fields
function getValueAK(field, ge) {

      // Local vars
      var fields;

      // If you don't pass in anything, you get an empty string
      if (!field) {
              return '';
      }

      // If no second parameter, assume this
      if (!ge) {
              ge = this;
      }

      // Split fields on dot
      fields = field.split('.');

      // If there is only one field
      if (fields.length === 1) {

              // If the field exists, return a string, else return empty string
              return ge[field] !== undefined ? String(ge[field]) : '';

      } else {

              // If there is more than one field, recurse
              return this.getValueAK(fields.slice(1).join("."), ge[fields.slice(0, 1)]);
      }

}


Reference : https://community.servicenow.com/community?id=community_question&sys_id=d71d8f69db9cdbc01dcaf3231f96...

***Mark Correct or Helpful if it helps.***