Can I reset and then reuse a GlideRecord?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-15-2024 08:17 AM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-15-2024 05:17 PM
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
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-18-2024 06:45 AM
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?
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-19-2024 08:42 AM
Hi @Danish Bhairag2,
I tried using this method but it gets a failure due to duplicate primary keys on the second gr.update().
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
03-19-2024 12:25 PM