How do I use gr.setValue();?

Anshul Duvey
Giga Contributor
 
8 REPLIES 8

Sandeep Rajput
Tera Patron
Tera Patron

Here is how you can use setValue() on a glide record.

var gr = new GlideRecord('incident');
gr.setLimit(1);
gr.query();
if(gr.next()){
    gr.setValue('short_description','New incident');
    gr.update();
}

Fore more information please refer to https://developer.servicenow.com/dev.do#!/reference/api/utah/server_legacy/c_GlideRecordAPI#r_GlideR...

 

Danish Bhairag2
Tera Sage
Tera Sage

Hi @Anshul Duvey  ,

 

`gr.setValue()` is a GlideRecord method used to set values for fields in a GlideRecord object. This method allows you to assign or update field values in records before inserting or updating them in the database.

 

Here's how you can use `gr.setValue()` in ServiceNow:

 

### Syntax:

 

gr.setValue('field_name', value);

 

 

### Example:

 

// Initialize a GlideRecord object for a specific table

var incidentGR = new GlideRecord('incident');

 

// Query for a specific record (if needed)

incidentGR.get('sys_id', 'incident_sys_id');

 

// Set/Update field values using setValue()

incidentGR.setValue('short_description', 'New Short Description');

incidentGR.setValue('priority', '2'); // Setting priority as '2' (Medium)

 

// Update the record in the database

incidentGR.update();

 

 

### Explanation:

- Initialize a `GlideRecord` object for the desired table.

- Optionally, query for a specific record using `get()` or `addQuery()`/`query()`.

- Use `setValue()` to set or update field values. Pass the field name and the desired value.

- Finally, perform `update()` to commit the changes to the database.

 

Ensure you replace `'field_name'` with the actual field name and `value` with the desired value you want to set. After updating the values using `setValue()`, call `update()` to save the changes to the record.

 

Remember to handle errors appropriately, especially when performing updates, to capture any issues during data manipulation.

 

Thanks,

Danish

 

Snehangshu Sark
Mega Guru

Hi @Anshul Duvey  ,

 

syntax: <glideobject>.setValue(<field name>,<new value>);

Example:

 

 

var gr = new GlideRecord('incident');
gr.addQuery('state=1');
gr.setLimit(1);
gr.query();
if(gr.next()){
    gs.info("name: "+gr.number+" @@ "+gr.short_description);
    gr.setValue('short_description','Test short description');
    gr.update();
}

 

 

Please mark this answered if I answered your question.

Hristo Ivanov
Kilo Sage

check out this article: 
https://www.servicenow.com/community/developer-forum/how-do-i-use-gr-setvalue/m-p/1419333

Please mark this response as correct and helpful if it helps you