Can I reset and then reuse a GlideRecord?

MBarrott
Mega Sage

Looking for more optimal coding practices and wanted to get some feedback. 

 

I have a script which is working great but I'm creating three GlideRecords that all reference the same table, albeit, they are ultimately doing different queries (inserts, deletions, record gathering etc).

 

Is there a way to clear out a GlideRecord and then simply reuse it, rather than declaring duplicates to accomplish the same thing? 

6 REPLIES 6

Danish Bhairag2
Tera Sage
Tera Sage

Hi @MBarrott ,

 

Yes, you can reuse a single GlideRecord instance for multiple operations by clearing its state after each use. Here's how you can do it:

 

// Declare a single GlideRecord instance

var gr = new GlideRecord('your_table_name');

 

// Query 1: Insert operation

gr.initialize(); // Clear the GlideRecord state

gr.setValue('field1', 'value1');

gr.setValue('field2', 'value2');

gr.insert();

 

// Query 2: Delete operation

gr.initialize(); // Clear the GlideRecord state

gr.addQuery('field1', 'value1');

gr.addQuery('field2', 'value2');

gr.deleteMultiple();

 

// Query 3: Record gathering

gr.initialize(); // Clear the GlideRecord state

gr.addQuery('field3', 'value3');

gr.query();

while (gr.next()) {

    // Process each record

}

 

In this example, `initialize()` method is called on the `gr` instance before each new operation to clear its state. This ensures that the GlideRecord is reset and ready to be used for the next query, insert, or delete operation without declaring multiple GlideRecord instances.

 

Thanks,

Danish

Hi @Danish Bhairag2

 

I had considered gr.initialize(); but I thought this was only really used when preparing to make an insert into the table referenced in the GlideRecord object?

Hi @Danish Bhairag2

 

I tried using this method but it gets a failure due to duplicate primary keys on the second gr.update(). 

Hi @MBarrott ,

 

Possible to share ur script which u using?

 

Thanks,

Danish