유용한 필드 스크립트

  • 릴리스 버전: Washingtondc
  • 업데이트 날짜 2024년 02월 01일
  • 읽기11분
  • 필드 사용자 지정 스크립트의 일반적인 사용 사례입니다.

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

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

    자동으로 필드 채우기

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

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

    클라이언트 스크립트 설정:
    • 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 색상 또는 &quot;파란색&quot; 또는 &quot;토마토&quot;와 같은 허용 가능한 CSS 색상
    • 레이블이 깜박이는 시간을 결정하는 정수:
      • 1초 플래시의 경우 2
      • 2초 플래시의 경우 0
      • -2 - 3초 플래시
      • -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 "Client callable" checkbox 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 .

    다음 서버 측 스크립트 예는 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);