필드 스크립트 사용 사례

  • 릴리스 버전: Australia
  • 업데이트 날짜 2026년 03월 12일
  • 소요 시간: 11분
  • 필드 커스터마이제이션 스크립트의 일반적인 사용 사례입니다.

    경고:
    여기에 설명된 커스터마이제이션은 특정 인스턴스에서 사용하기 위해 개발되었으며 에서 지원되지 Now Support않습니다. 이 메서드는 있는 그대로 제공되며 구현하기 전에 철저하게 테스트해야 합니다. 이 커스터마이제이션에 대한 모든 질문과 의견을 커뮤니티 포럼에 게시하십시오.

    자세한 내용은 서버 API 참조 문서를 참조하십시오.

    필드 자동 채우기

    다음 예는 클라이언트 스크립트를 사용하여 선택한 하위 범주를 기준으로 간단한 설명을 자동으로 채우는 방법을 보여줍니다.

    이 경우 테이블에 하위 범주 = 암호 및 간단한 설명 = 암호 재설정이 있는 기록이 있는 경우입니다. 사용자가 인시던트 양식에서 암호하위 범주를 선택하면 클라이언트 스크립트가 일치하는 기록을 조회하고 짧은 설명을 암호 재설정과 동일하게 설정합니다.

    클라이언트 스크립트 설정:
    • Type = 변경 시
    • Table name = 인시던트
    • Field name = 하위 범주
    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 태그 사용 안 함

    이 코드는 실행되지 않는 버전으로 태그를 대체하여 설명간단한 설명 필드의 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)");}
    }

    필드에서 선행 및 후행 공백 제거

    이 스크립트 예시에서는 sys_user의 필드 LastName 에서 후행 및 선행 공백 FirstName 을 트리밍합니다.
    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();}}
    }

    필드 레이블을 플래시로 만들기

    다음 클라이언트 스크립트 예시는 인시던트의 숫자 필드에 대한 것입니다. 레이블이 2초 동안 깜박입니다.
    g_form.flash("incident.number","#FFFACD",0);
    flash 메서드의 인수는 다음과 같습니다.
    • tablename.fieldname
    • RGB 색상 또는 허용되는 CSS 색상(예: "파란색" 또는 "토마토")입니다.
    • 레이블이 깜박이는 시간을 결정하는 정수:
      • 2초 플래시의 경우 1
      • 0의 경우 2초 플래시
      • 3초 깜박임의 경우 -2
      • 4초 플래시의 경우 -4
    주:
    필드 레이블을 지정된 색상으로 지정하려면 이 인수를 지정하지 마십시오.

    필드 레이블을 굵게 만들기

    이 클라이언트 스크립트는 특정 필드의 레이블을 굵게 만듭니다. 이 경우 필드는 인시던트 테이블짧은 설명입니다.
    function onLoad(){
      var l = g_form.getLabel('incident.short_description');
      l.style.fontWeight = 'bold';}

    필드를 읽기 전용으로 설정

    이 onLoad 클라이언트 스크립트는 인시던트 [incident] 테이블의 다음 필드를 읽기 전용으로 만듭니다.
    • 인시던트 상태
    • 영향도
    • 긴급도
    • 우선순위
    • 구성 항목
    • 할당 대상
    또한 스크립트는 읽기 전용 참조 필드(구성 항목할당 대상)에 대한 돋보기를 제거합니다.
    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);}}

    필드에서 현재 날짜/시간 설정

    클라이언트 스크립트 및 스크립트 포함에서 날짜 및 시간 값을 설정할 수 있습니다.

    클라이언트 스크립트
    다음 두 줄을 사용하여 날짜/시간 필드에서 현재 날짜와 시간을 설정할 수 있습니다. 이 접근 방식은 값을 적절한 형식과 적절한 시간대로 가져오는 문제를 우회합니다.
    var ajax = new GlideAjax('MyDateTimeAjax');
      ajax.addParam('sysparm_name','nowDateTime');
      ajax.getXML(function(){
        g_form.setValue('put your field name here', ajax.getAnswer());});
    클라이언트를 사용하여 서버 측 스크립트를 실행하는 방법에 대한 자세한 내용은 GlideAjax를 참조하십시오.
    시스템 스크립트 포함
    // Be sure the Glide AJAX enabled option is checked
     
    var MyDateTimeAjax = Class.create();
    MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor,{
      nowDateTime:function(){
        return gs.nowDateTime();}});

    타이머 필드를 필드 이름으로 전환

    다음 클라이언트 스크립트는 특정 필드 이름에 따라 타이머 필드를 전환합니다.
    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 필드 값 수정

    다음 서버 측 스크립트 예시는 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(); (GlideElement)
    //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.addSeconds(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);
     
    //set the value of the GlideDateTime object to the current session timezone/format
    GlideSession.get().setTimeZoneName('US/Eastern');
    gdt.setDisplayValue('2018-2-28 00:00:00');
    gs.info('In ' + GlideSession.get().getTimeZoneName() + ": " + gdt.getDisplayValue());
    참조 :