{"revision":"c10276e953456835cdbb1f3a60d58ae1980be353","document":{"id":676,"path":"api-reference/scripts/r_UsefulFieldScripts.md","title":"Field script use cases","bundle":null,"doc_type":null,"release":"australia","body":"\n# Field script use cases\n\nCommon use cases for field customization scripts.\n\n**Warning:** The customization described here was developed for use in specific instances, and is not supported by Now Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community [forum](http://community.service-now.com/).\n\nFor more information, see [Server API reference](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/api-server.md).\n\n## Automatically populate a field\n\nThe following example shows how to use a client script to auto-fill a **Short Description** based on the selected **Subcategory**.\n\nIn this case, if the table has a record with **Subcategory** = Password and **Short Description** = Password Reset. When the user selects the **Subcategory** of **Password** on the Incident form, a client script looks up the matching record and sets **Short Description** equal to Password Reset.\n\nClient script settings:\n\n-   **Type** = onChange\n-   **Table name** = incident\n-   **Field name** = Subcategory\n\n```\nfunction onChange(control, oldValue, newValue, isLoading){\n    if(isLoading){return;}\n    var newrec = gel('sys_row');\n    //Check if new record\n    if (newrec.value == -1) {\n        var lookup = new GlideRecord('u_short_desc_lookup');\n        lookup.addQuery('u_subcategory', g_form.getValue('subcategory'));\n        lookup.query();\n        var temp; //temp var - reusable\n        if(lookup.next()){\n            temp = lookup.u_short_description;\n            if(null != temp) {\n                //Set the form value from lookup if there is a lookup value\n                g_form.setValue('short_description', temp);\n            } else {\n                g_form.setValue('short_description',\"\");\n                }\n          } else {\n              //If a lookup record does not exist based on lookup.addQuery\n              //Then set to UNDEFINED or NULL depending on type\n              g_form.setValue('short_description',\"\");\n              }\n     }\n}\n```\n\n## Disable HTML tags in descriptions\n\nThis code disables HTML tags in **Description** and **Short Description** fields by substituting the tags with non-executing versions.\n\n```\ndoit();\n \nfunction doit(){ \n var desc = current.description.toString();\n var shdesc = current.short_description.toString();\n if(desc.indexOf('script>')>-1|| shdesc.indexOf('script>')>-1){\n   desc = desc.replace(/<script>/g,\"(script)\");\n   current.description = desc.replace(/<\\/script>/g,\"(\\/script)\");\n   shdesc = shdesc.replace(/<script>/g,\"(script)\");\n   current.short_description = shdesc.replace(/<\\/script>/g,\"(\\/script)\");}\n}\n```\n\n## Eliminate leading and trailing spaces in fields\n\nThis example of the script trims trailing and leading spaces in the **FirstName** and **LastName** fields of the sys\\_user.\n\n```\ndoit();\n \nfunction doit(){ \n  var now_GR =new GlideRecord('sys_user');\n  gr.query();\n  while(gr.next()){\n    if((gr.first_name.toString().length!= gr.first_name.toString().trim().length)||(gr.last_name.toString().length!= gr.last_name.toString().trim().length)){\n     gr.first_name= gr.first_name.toString().trim();\n     gr.last_name= gr.last_name.toString().trim();\n     gr.autoSysFields(false);\n     gr.update();}}\n}\n```\n\n## Make a field label flash\n\nThe following client script example is for the number field on incident. The label flashes for two seconds.\n\n```\ng_form.flash(\"incident.number\",\"#FFFACD\",0);\n```\n\nThe arguments for the flash method are as follows:\n\n-   **tablename.fieldname**\n-   RGB color or acceptable CSS color like \"blue\" or \"tomato\"\n-   Integer that determines how long the label flashes:\n    -   2 for a 1-second flash\n    -   0 for a 2-second flash\n    -   -2 for a 3-second flash\n    -   -4 for a 4-second flash\n\n**Note:** Do not specify this argument if you want the field label colored the specified color.\n\n## Make a field label bold\n\nThis client script makes the label of a particular field bold. In this case, the field is the **Short Description** on the **Incident Table**.\n\n```\nfunction onLoad(){\n  var l = g_form.getLabel('incident.short_description');\n  l.style.fontWeight = 'bold';}\n```\n\n## Make fields read-only\n\nThis onLoad client script makes the following fields on the Incident \\[incident\\] table read-only:\n\n-   **Incident state**\n-   **Impact**\n-   **Urgency**\n-   **Priority**\n-   **Configuration item**\n-   **Assigned to**\n\nThe script also removes the magnifying glass for the read-only Reference Fields \\(**Configuration item** and **Assigned to**\\).\n\n```\nfunction onLoad(){\nvar incidentState = g_form.getValue('incident_state');\nif( incidentState == '6'|| incidentState == '7'){\n   g_form.setReadonly('incident_state',true);\n   g_form.setReadonly('impact',true);\n   g_form.setReadonly('urgency',true);\n   g_form.setReadonly('priority',true);\n   g_form.setReadonly('cmdb_ci',true);\n   g_form.setReadonly('assigned_to',true);}}\n```\n\n## Set current date/time in field\n\nYou can set date and time values in client scripts and script includes.\n\n-   **Client script**\n\n    You can use the following two lines to set the current date and time in a date/time field. This approach bypasses the problem of getting the value into the proper format and proper time zone.\n\n    ```\n    var ajax = new GlideAjax('MyDateTimeAjax');\n      ajax.addParam('sysparm_name','nowDateTime');\n      ajax.getXML(function(){\n        g_form.setValue('put your field name here', ajax.getAnswer());});\n    ```\n\n    For more information on running server-side scripts with the client, refer to [GlideAjax](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/scripts/p_AJAX.md).\n\n-   **System script include**\n\n    ```\n    // Be sure the Glide AJAX enabled option is checked\n     \n    var MyDateTimeAjax = Class.create();\n    MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor,{\n      nowDateTime:function(){\n        return gs.nowDateTime();}});\n    ```\n\n\n## Toggle the timer field by field name\n\nThe following client script toggles the timer field based on a particular field name.\n\n```\nfunction toggleTimerByFieldName(fieldName){\n //Step 1: Find the timer object\n //timeObjectName: the timer objects name as it would normally be referenced\n //timeObjectHidden: the hidden input node in the field td\n //timeObjectParent: the parent td node containing the field and it's constituent nodes\n //timeObjectFields: anchor tag with onclick to stop timer\n \n var timeObjectName = fieldName;\n var timeObjectHidden = gel(timeObjectName);\n \n //Step 2: simulate click stop button\n var timeObjectParent;\n var timeObjectFields;\n \n //verify that we got the correct object\n if(timeObjectHidden.type==\"hidden\"){\n \n    //Get Parent td node\n    timeObjectParent = timeObjectHidden.parentNode;\n \n    //Get input fields\n    timeObjectFields = timeObjectParent.getElementsByTagName(\"input\");\n \n    //simulate click of stop button\n    var timerTestString =\"paused\";\n    var timerImg;\n \n    //loop through input objects looking for the pause timer object\n    for(var elIt=0; elIt < timeObjectFields.length; elIt++){\n      if(timeObjectFields[elIt].id.match(timerTestString)){\n        if(timeObjectFields[elIt].value==\"false\"){\n          timeObjectFields[elIt].value=\"true\";\n          timerImg = timeObjectParent.getElementsByTagName(\"img\")[0];\n          timerImg.src=\"images/timer_start.gifx\";}\n      elseif(timeObjectFields[elIt].value==\"true\"){\n          timeObjectFields[elIt].value=\"false\";\n          timerImg = timeObjectParent.getElementsByTagName(\"img\")[0];\n          timerImg.src=\"images/timer_stop.gifx\";}}}}}\n```\n\n## Modify GlideDateTime field values\n\nThe following server-side script example shows how to modify values using the GlideDateTime API. The same concept also applies to the GlideDate object.\n\n**Note:** The following script is only intended for global applications.\n\n```\n//You first need a GlideDateTime object\n//this can be from instantiating a new object \"var gdt = new GlideDateTime()\"\n//or getting the object from a GlideDateTime field\n//getting the field value (for example: var gdt = current.start_date) only returns the string value, not the object\n//to get the object use var gdt = current.start_date.getGlideObject(); (GlideElement)\n//now gdt is a GlideDateTime object\nvar gdt = current.start_date.getGlideObject();\n \n//All methods can use negative values to subtract intervals\n \n//add 1 hour (60 mins * 60 secs)\ngdt.addSeconds(3600);\n \n//add 1 day\ngdt.addDaysLocalTime(1);\n \n//subtract 1 day\ngdt.addDaysLocalTime(-1);\n \n//add 3 weeks\ngdt.addWeeksLocalTime(3);\n \n//subtract 6 months\ngdt.addMonthsLocalTime(-6);\n \n//add 1 year, representing the date and time using the UTC timezone instead of the local user's timezone.\ngdt.addYearsUTC(1);\n \n//set the value of the GlideDateTime object to the current session timezone/format\nGlideSession.get().setTimeZoneName('US/Eastern');\ngdt.setDisplayValue('2018-2-28 00:00:00');\ngs.info('In ' + GlideSession.get().getTimeZoneName() + \": \" + gdt.getDisplayValue());\n```\n\nSee also:\n\n-   [GlideDateTime](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/scripts/p_GlideServerAPIs.md)\n-   [GlideDate - Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/GlideDateAPI.md)\n-   [GlideDate - Scoped](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/c_GlideDateScopedAPI.md)\n-   [GlideDateTime - Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/c_GlideDateTimeAPI.md)\n-   [GlideDateTime - Scoped](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/c_GlideDateTimeScoped.md)\n-   [GlideElement - Global](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/c_GlideElementAPI.md)\n-   [GlideElement - Scoped](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/c_GlideElementScopedAPI.md)\n-   [GlideTime - Scoped](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/server-api-reference/c_GlideTimeScopedAPI.md)\n\n-   **[Approval assignment scripts](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/scripts/r_UsefulApprovalAssignmentScripts.md)**  \nThis is a searchable version of the useful approval and assignment scripts.\n\n**Parent Topic:**[Useful scripts](https://raw.githubusercontent.com/ServiceNow/ServiceNowDocs/australia/markdown/australia/api-reference/scripts/usefulScripts.md)\n\n"}}