Autopopulating first result from sorted list in the SRD

Akshay03
Kilo Sage

 

Hello,

I've successfully obtained a list of Configuration Items (CIs) using a script include. However, I now aim to automatically populate a variable with the CI that is the latest created. How can I achieve this?

1 ACCEPTED SOLUTION

Brent Sutton
Mega Sage

Hi @Akshay03, you just need to amend your script include to order the returned results by the Created On [sys_created_on] field so the CI that was created last is the first record in the array result. You then populate your variable using the first item in your array:

 

A very simple example of a script include function that would do this is shown below:

 

getNewestConfigurationItems: function() {
    var ci = new GlideRecord('cmdb_ci');
    ci.orderByDesc('sys_created_on');
    ci.setLimit(10);
    ci.query();
    var result = [];
    while (ci.next()) {
      result.push(ci);
    }
    return result;
  },

 

Please mark as correct if this answered your question.

 

 

View solution in original post

2 REPLIES 2

Brent Sutton
Mega Sage

Hi @Akshay03, you just need to amend your script include to order the returned results by the Created On [sys_created_on] field so the CI that was created last is the first record in the array result. You then populate your variable using the first item in your array:

 

A very simple example of a script include function that would do this is shown below:

 

getNewestConfigurationItems: function() {
    var ci = new GlideRecord('cmdb_ci');
    ci.orderByDesc('sys_created_on');
    ci.setLimit(10);
    ci.query();
    var result = [];
    while (ci.next()) {
      result.push(ci);
    }
    return result;
  },

 

Please mark as correct if this answered your question.

 

 

Tai Vu
Kilo Patron
Kilo Patron

Hi @Akshay03 

Let's use the API below to order the query set in descending order of a specific field.

orderByDesc(String, fieldName)

 

Cheers,

Tai Vu