---
sourceDocument: Xanadu API リファレンス
sourceDocumentLink: https://servicenow-prod.fluidtopics.net/r/ja-JP/xanadu/api-reference

 Release :

    - xanadu

ft:locale :

    - ja-JP

ft:publication_title :

    - Xanadu API リファレンス

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# 有用なフィールドスクリプト

# 有用なフィールドスクリプト {#ariaid-title1}

* リリースバージョン: Xanadu
* 
* 更新日 2024年08月01日
* 
* ![](https://www.servicenow.com/docs/portal-asset/ico-clock) 所要時間：11分

フィールドカスタマイズスクリプトの一般的なユースケース。
警告:  
ここに記載されているカスタマイズは、特定のインスタンスで使用するために開発されたものであり、Now Support ではサポートされていません。この方法は現状のまま提供され、実装の前に完全にテストする必要があります。このカスタマイズに関するすべての質問およびコメントは、コミュニティ[フォーラム](http://community.service-now.com/)に投稿してください。

詳細については、「[サーバー API リファレンス](https://servicenow-prod.fluidtopics.net/h2455bzcM~MmG2nNzgrT8A "スクリプトでサーバー API を使用して、アプリケーションの機能を変更したり、新しいアプリケーションを作成したりします。")」を参照してください。

## フィールドの自動入力 {#r_UsefulFieldScripts__section_upr_nvx_mtb}

次の例は、クライアントスクリプトを使用して、選択した \[サブカテゴリ\] に基づいて簡単な説明を自動入力する方法を示しています。

この場合、テーブルには \[サブカテゴリ\] = パスワード、\[簡単な説明\] = パスワードリセットのレコードがあります。ユーザーがインシデントフォームで \[サブカテゴリ\] に \[パスワード\] を選択した場合、クライアントスクリプトは一致するレコードを検索し、\[簡単な説明\] をパスワードリセットに設定します。  
クライアントスクリプト設定：

* Type = onChange
* Table name = incident
* Field name = Subcategory

{#r_UsefulFieldScripts__ul_ix3_hyx_mtb}

    function onChange(control, oldValue, newValue, isLoading){
        if(isLoading){return;}
        var newrec = gel('sys_row');
        //Check if new record
        if (newrec.value == -1) {
            var lookup = new GlideRecord('u_short_desc_lookup');
            lookup.addQuery('u_subcategory', g_form.getValue('subcategory'));
            lookup.query();
            var temp; //temp var - reusable
            if(lookup.next()){
                temp = lookup.u_short_description;
                if(null != temp) {
                    //Set the form value from lookup if there is a lookup value
                    g_form.setValue('short_description', temp);
                } else {
                    g_form.setValue('short_description',"");
                    }
              } else {
                  //If a lookup record does not exist based on lookup.addQuery
                  //Then set to UNDEFINED or NULL depending on type
                  g_form.setValue('short_description',"");
                  }
         }
    }

## 説明の HTML タグを無効にする {#r_UsefulFieldScripts__section_o2z_kxx_mtb}

このコードは、HTML タグを非実行バージョンに置き換えることで、\[説明\] および \[簡単な説明\] フィールド内の HTML タグを無効にします。

    doit();
     
    function doit(){ 
     var desc = current.description.toString();
     var shdesc = current.short_description.toString();
     if(desc.indexOf('script>')>-1|| shdesc.indexOf('script>')>-1){
       desc = desc.replace(/<script>/g,"(script)");
       current.description = desc.replace(/<\/script>/g,"(\/script)");
       shdesc = shdesc.replace(/<script>/g,"(script)");
       current.short_description = shdesc.replace(/<\/script>/g,"(\/script)");}
    }

## フィールドの先頭と末尾のスペースの削除 {#r_UsefulFieldScripts__section_kbd_gxx_mtb}

このスクリプトの例では、sys_user の FirstName および LastName フィールドの末尾と先頭のスペースをトリミングします。

    doit();
     
    function doit(){ 
      var now_GR =new GlideRecord('sys_user');
      gr.query();
      while(gr.next()){
        if((gr.first_name.toString().length!= gr.first_name.toString().trim().length)||(gr.last_name.toString().length!= gr.last_name.toString().trim().length)){
         gr.first_name= gr.first_name.toString().trim();
         gr.last_name= gr.last_name.toString().trim();
         gr.autoSysFields(false);
         gr.update();}}
    }

## フィールドラベルを点滅させる {#r_UsefulFieldScripts__section_lnv_swx_mtb}

次のクライアントスクリプトの例は、インシデントの番号フィールド用です。ラベルが 2 秒間点滅します。

    g_form.flash("incident.number","#FFFACD",0);

flash メソッドの引数は次のとおりです。

* tablename.fieldname
* RGB カラーまたは受け入れ可能な CSS カラー (「blue」や「tomato」など)
* ラベルの点滅時間を決定する整数：
  * 1 秒間点滅の場合は 2
  * 2 秒間点滅の場合は 0
  * 3 秒間点滅の場合は -2
  * 4 秒間点滅の場合は -4
  {#r_UsefulFieldScripts__ul_xky_hdr_4x}
{#r_UsefulFieldScripts__ul_qh5_kgr_4x}  
注:  
指定した色でフィールドラベルを表示する場合は、この引数を指定しないでください。

## フィールドラベルを太字にする {#r_UsefulFieldScripts__section_y4k_xwx_mtb}

このクライアントスクリプトは、特定のフィールドのラベルを太字にします。この場合、フィールドは \[インシデントテーブル\] の \[簡単な説明\] です。

    function onLoad(){
      var l = g_form.getLabel('incident.short_description');
      l.style.fontWeight = 'bold';}

## フィールドを読み取り専用にする {#r_UsefulFieldScripts__section_bhw_4vx_mtb}

この onLoad クライアントスクリプトにより、インシデント \[incident\] テーブルの次のフィールドは読み取り専用になります。

* インシデント状況
* 影響
* 緊急度
* 優先度
* 構成アイテム
* アサイン先
{#r_UsefulFieldScripts__ul_pbz_tzx_mtb}  
また、このスクリプトにより、読み取り専用の参照フィールド (\[構成アイテム\] および \[アサイン先\]) の虫眼鏡が削除されます。

    function onLoad(){
    var incidentState = g_form.getValue('incident_state');
    if( incidentState == '6'|| incidentState == '7'){
       g_form.setReadonly('incident_state',true);
       g_form.setReadonly('impact',true);
       g_form.setReadonly('urgency',true);
       g_form.setReadonly('priority',true);
       g_form.setReadonly('cmdb_ci',true);
       g_form.setReadonly('assigned_to',true);}}

## フィールドへの現在の日付/時刻の設定 {#r_UsefulFieldScripts__section_vpr_nvx_mtb}

クライアントスクリプトとスクリプトインクルードで日付と時刻の値を設定できます。

クライアントスクリプト
:   次の 2 行を使用して、日付/時刻フィールドに現在の日付と時刻を設定できます。このアプローチでは、値の適切な形式とタイムゾーンへの変換の問題を回避できます。

        var ajax = new GlideAjax('MyDateTimeAjax');
          ajax.addParam('sysparm_name','nowDateTime');
          ajax.getXML(function(){
            g_form.setValue('put your field name here', ajax.getAnswer());});

:   クライアントでのサーバーサイドスクリプトの実行の詳細については、「[GlideAjax](https://servicenow-prod.fluidtopics.net/ld_tMHghRk9h4~Aq2ZI8Fg#p_AJAX "AJAX (非同期 JavaScript および XML) は、非同期 Web アプリケーションの作成に使用される、相互に関連するクライアントサイド開発手法の集まりです。")」を参照してください。

システムスクリプトインクルード
:

        // Be sure the "Client callable" checkbox is checked
         
        var MyDateTimeAjax = Class.create();
        MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor,{
          nowDateTime:function(){
            return gs.nowDateTime();}});

## フィールド名でのタイマーフィールドの切り替え {#r_UsefulFieldScripts__section_xzg_mvx_mtb}

次のクライアントスクリプトは、特定のフィールド名に基づいてタイマーフィールドを切り替えます。

    function toggleTimerByFieldName(fieldName){
     //Step 1: Find the timer object
     //timeObjectName: the timer objects name as it would normally be referenced
     //timeObjectHidden: the hidden input node in the field td
     //timeObjectParent: the parent td node containing the field and it's constituent nodes
     //timeObjectFields: anchor tag with onclick to stop timer
     
     var timeObjectName = fieldName;
     var timeObjectHidden = gel(timeObjectName);
     
     //Step 2: simulate click stop button
     var timeObjectParent;
     var timeObjectFields;
     
     //verify that we got the correct object
     if(timeObjectHidden.type=="hidden"){
     
        //Get Parent td node
        timeObjectParent = timeObjectHidden.parentNode;
     
        //Get input fields
        timeObjectFields = timeObjectParent.getElementsByTagName("input");
     
        //simulate click of stop button
        var timerTestString ="paused";
        var timerImg;
     
        //loop through input objects looking for the pause timer object
        for(var elIt=0; elIt < timeObjectFields.length; elIt++){
          if(timeObjectFields[elIt].id.match(timerTestString)){
            if(timeObjectFields[elIt].value=="false"){
              timeObjectFields[elIt].value="true";
              timerImg = timeObjectParent.getElementsByTagName("img")[0];
              timerImg.src="images/timer_start.gifx";}
          elseif(timeObjectFields[elIt].value=="true"){
              timeObjectFields[elIt].value="false";
              timerImg = timeObjectParent.getElementsByTagName("img")[0];
              timerImg.src="images/timer_stop.gifx";}}}}}

## GlideDateTime フィールド値の変更 {#r_UsefulFieldScripts__section_k4g_jvx_mtb}

次の例では、サーバーサイドスクリプトを使用して GlideDateTime フィールドにアクセスします。  
次のサーバーサイドスクリプトの例は、GlideDateTime API を使用して値を変更する方法を示しています。同じ概念が GlideDate オブジェクトにも適用されます。

    //You first need a GlideDateTime object
    //this can be from instantiating a new object "var gdt = new GlideDateTime()"
    //or getting the object from a GlideDateTime field
    //getting the field value (for example: var gdt = current.start_date) 
    //only returns the string value, not the object
    //to get the object use var gdt = current.start_date.getGlideObject();
    //now gdt is a GlideDateTime object
    var gdt = current.start_date.getGlideObject();
     
    //All methods can use negative values to subtract intervals
     
    //add 1 hour (60 mins * 60 secs)
    gdt.addSecondsLocalTime(3600);
     
    //add 1 day
    gdt.addDaysLocalTime(1);
     
    //subtract 1 day
    gdt.addDaysLocalTime(-1);
     
    //add 3 weeks
    gdt.addWeeksLocalTime(3);
     
    //subtract 6 months.
    gdt.addMonthsLocalTime(-6);
     
    //add 1 year, representing the date and time using the UTC timezone instead of the local user's timezone.
    gdt.addYearsUTC(1);


