Background script (it should not create new records)

ss123
Tera Contributor

Hi! I'm having a hard time fixing this background script below. The script is working however, it creates new records in the vtb_task table. Am I missing something? Thank you in advance 🙂

 

var current = new GlideRecord('vtb_card');
current.query();
while (current.next()){
var vtbtask = new GlideRecord('vtb_task');
vtbtask.addQuery('sys_id', current.task);
vtbtask.query();
if (vtbtask.next()) {
vtbtask.setValue('u_choice_2', 'no');

} else {
vtbtask.setValue('u_choice_2', 'yes');
}
vtbtask.update();
}

19 REPLIES 19

Aman Kumar S
Kilo Patron

Hi,

I believe you should refrain from using current as a variable name, just confuses the context

 

This must be happening because of this block:

if (vtbtask.next()) {
vtbtask.setValue('u_choice_2', 'no');

} else {
vtbtask.setValue('u_choice_2', 'yes');
}

So what you are doing here, you are trying to do, you are first glideing the vtb_card table and then the vtb_task table.

And in the 2nd Gliderecord, you are looking up the record for vtb_task, and it a match is found you are setting the value to no and if no match is found for the sys_id you are setting the value to yes.

That is the issue with else here, you are not pointing to any record here, so you will have to set the context a lil bit, what exactly you are trying to achieve.

 

 

 

Best Regards
Aman Kumar

Hi @Aman Kumar S 

 

What I'm trying to achieve is that I need to update existing records in vtb_task table, that's why  I used the script below:

 

if (vtbtask.next()) {
vtbtask.setValue('u_choice_2', 'no');

} else {
vtbtask.setValue('u_choice_2', 'yes');
}

Actually, this is a Business Rule applied in Background script. Well the business rule only runs to newly created records, right?

 

Thanks,

Sab

The BR would run on the Insert/Update based upon your selections in When to Run section.

Let me try to break it down a bit:

var vtbtask = new GlideRecord('vtb_task');// Gliding the vtb task table
vtbtask.addQuery('sys_id', current.task);// passing sys_id to look for an exisitng record
vtbtask.query();
if (vtbtask.next()) {// if record exists with the sys_id
vtbtask.setValue('u_choice_2', 'no');

} else {
vtbtask.setValue('u_choice_2', 'yes');// if record doesn't exist set the value and since there is no existing record, it is ending up creating a new record.
}
vtbtask.update();// this results in insertion for else case, for if case it just updates the existing record

 

Hope this makes things clear.

 

Best Regards
Aman Kumar

Hi @Aman Kumar S 

Thanks for breaking the it down for me. I was just wondering, do I need to add a script to so it would not create new records and just update existing ones?

 

Thanks,

Sab