Skip the dependent record creation if new record name is existing

rmaroti
Tera Contributor

Hi Everyone,

 

I have write the code where i'm not able to skip the condition when we are creating new record in  "pc_software_cat_item" this table and new record name is already exist then need to skip the record of "io_set_item" this table which is dependent record can someone help where i'm doing mistakes when record name is unique it is creating dependent record which is expected but in case of duplication it is also creating depending record which is unexpected behavior.

 

(function executeRule(current, previous /*null when async*/ ) {
    if(current.name){
        var gr1 = new GlideRecord('pc_software_cat_item');
        gr1.addQuery('name', current.name);
        gr1.query();
        if (!gr1.next()) {
            // If unique name record create,  then create a below new one record
            var gr = new GlideRecord('io_set_item');
            gr.addQuery('sc_cat_item', current.sys_id);
            gr.query();

            if (!gr.next()) {
                // If no record exists, create a new one
                var variableSetSysId = gs.getProperty('sam.variable_set_sys_id'); // CAR_SAM_Variable system properties.
                gr.initialize();
                gr.sc_cat_item = current.sys_id; // Reference to the Catalog Item
                gr.variable_set = variableSetSysId; // Reference to the Variable Set
                gr.insert(); // Insert the new record into the io_set_item table

            }
        }
    }

})(current, previous);
2 REPLIES 2

Nilesh Pol
Tera Guru

@rmaroti You need to properly skip the dependent record creation when a duplicate exists in pc_software_cat_item. Modify your script like this:

(function executeRule(current, previous /*null when async*/) {
if (current.name) {
var gr1 = new GlideRecord('pc_software_cat_item');
gr1.addQuery('name', current.name);
gr1.query();

if (gr1.hasNext()) {
gs.info("Skipping dependent record creation because a duplicate name exists in pc_software_cat_item.");
return; // Exit the script to prevent further execution
}

var gr = new GlideRecord('io_set_item');
gr.addQuery('sc_cat_item', current.sys_id);
gr.query();

if (!gr.hasNext()) {
var variableSetSysId = gs.getProperty('sam.variable_set_sys_id'); 
gr.initialize();
gr.sc_cat_item = current.sys_id; 
gr.variable_set = variableSetSysId; 
gr.insert(); 

gs.info("New dependent record created in io_set_item.");
}
}
})(current, previous);

SwathiPedireddy
Kilo Sage

Hi @rmaroti 

I don't see any issues with your script and it is working for me. Please give some logs in the script and check. Share BR conditions and on which table it is written if possible

Thanks,

Swathi