Code snippet(不定期更新)

1. Fire the notification event

gs.eventQueue("event_name", current, null, null);
parm1: event name
parm2: glide record
parm3: sys id if notification event 1 checkbox is ticked. if not it will work in email script event parm.
parm4: as top.

2. Copy attachments from one table to another

new GlideSysAttachment.copy("source_table_name", source_record_sys_id, "target_table_name", target_record_sys_id);

3.The client script to reload a form

reloadWindow(window);

4.Get the display value for a language

var lang = gs.getSession().getLanguage(); // puts the user's current language in a variable
gs.getSession().setLanguage("es"); // sets the session language to whatever you want, this one is Spanish
gs.print(gr.title.getDisplayValue()); // prints the Spanish translation of the "title" field of the GlideRecord variable "gr"
gs.getSession().setLanguage(lang); // sets the langauge back to what it was

5.Set Attachment to be Mandatory

try { //Works in non-portal ui
    var attachments = document.getElementById('header_attachment_list_label');
    if (attachments.style.visibility == 'hidden' || attachments.style.display == 'none' ) {
        g_form.addErrorMessage('You must attach the completed form before submitting this request.');
        return false;
    }
} catch(e) { //For Service Portal
    var count = getSCAttachmentCount(); //this function was created in UI script in global scope.
    if(count <= 0) {
        g_form.addErrorMessage('You must attach the completed form before submitting this request.');
        return false;
    }
}

//need write to UI Script file and Include in the Portal Themes
function getSCAttachmentCount() {
    var length;
    try {
        length = angular.element("#sc_cat_item").scope().attachments.length;
    } catch(e) {
        length = -1;
    }
    return length;
}

6. Calculate the next workday by Schedule

var duration += '3 00:00:00';
var dayDuration = new GlideDuration(duration);    
var startDate = new GlideDateTime(created_on);    
var slaDef = new SLADefinition();
slaDef.setSchedule(scheduleId);   //need to create a schedule
slaDef.setDuration(dayDuration);
var endDate = slaDef.getExampleBreachTime(startDate);

7.Loop to make fields to be read only

var fields = g_form.getEditableFields();
for (var x = 0; x < fields.length; x++) {
if (fields[x] != 'work_notes' && fields[x] != 'work_start' &&fields[x] != 'work_end') {
    g_form.setReadOnly(fields[x], true);
   }
}

8.Get the label for a choice list value

var choiceValue = g_form.getValue(<fieldName>); 
var choiceLabel = g_form.getOption(<fieldName>, choiceValue).text;

9.Get Display Value in Client Script for Reference field (unsupport Service Portal)

var user = g_form.getReference('caller_id', callBack);
    function callBack(user){
       alert(user.name);
}

10.How to get the first comment in activity log

current.comments.getJournalEntry(-1)

11.Convert duration to seconds in javascript

var slaDuration = current.sla.duration;
var duration = slaDuration.getGlideObject().getNumericValue();
var durationSeconds = (duration/1000);

12.How to get the ID of an Annotation in form (Annotation can't work on Service Portal)

var refs = document.getElementsByClassName("annotation-wrapper");
refs[3].style.display = 'none';

13. Use GlideRecord in Client Script

var gr_user = new GlideRecord("sys_user");
gr_user.addQuery("active",true);
gr_user.query(function(gr_user){
    while(gr_user.next()){
            //do something
            g_form.getValue("name");
    }
});

14. How to convert attachment to base64 code as string

var attachment_sysid = "003a3ef24ff1120031577d2ca310c74b"/* some sys_id string */;
var gr = new GlideRecord("sys_attachment");
if (gr.get(attachment_sysid)) {
       var ga = new GlideSysAttachment();
       var binData = ga.getBytes(gr); //getBytes function is not list in api doument but it can work.
      var base64Data = GlideStringUtil.base64Encode(binData); //GlideStringUtil is global common util but not list in api document
} 
//使用GlideSysAttachment轉換出的數據會有5M的限制,可以使用如下方式突破5M限制。
        var gsa = GlideSysAttachmentInputStream(gr.getValue("sys_id"));
        var baos = new Packages.java.io.ByteArrayOutputStream();
        gsa.writeTo(baos);
        var binData = baos.toByteArray();
                var base64Data = GlideStringUtil.base64Encode(binData);
                 var urlData = GlideStringUtil.urlEncode(base64Data);
                 ......

*15. How to sort Reference type with order field by out of box.

find attribute option in default value tab and type as below.
ref_ac_order_by=u_order /*u_order is customer filed*/

Reference類型的variable,在attribute設置下拉框中多個column提示
ref_auto_completer=AJAXTableCompleter,ref_ac_columns=email,ref_ac_order_by=sys_class_name,ref_ac_columns_search=true

*16. Change the category of all 'software' incidents to 'hardware' without updating sys fields.

var gr = new GlideRecord('incident');
gr.addQuery('category', 'software');
gr.query();
while(gr.next()){
   gr.category = 'hardware';
     gr.setWorkflow(false); //Do not run business rules
     gr.autoSysFields(false); //Do not update system fields
   gr.update();
}

*17. UI Action Validation

//UI Action中勾選Client,並設置唯一自定義Action名字iedRejectComments。
//UI Action中勾選Client後的代碼爲客戶端和服務端代碼混合。
function checkComments(){
    var flag = confirm('Are you sure you want to reject the request?');
    if(flag){
        g_form.clearMessages();
        g_form.setValue("state",107);//觸發已設置好的UI policy:"當狀態爲107的時候將某字段設置爲強制填寫"
        gsftSubmit(null, g_form.getFormElement(), 'iedRejectComments');
        return true;
    }
    return false;
}
if (typeof window == 'undefined') callServerSide();

function callServerSide(){
    current.state = 107;
    current.update();
    action.setRedirectURL(current);
    gs.addInfoMessage('The request has been rejected.');   
}

*18. save base64 file to specified record

var attachement = new GlideSysAttachment();
var base64String = File; //File爲base64Encode的字符串代碼
var attachment_sys_id = attachement.writeBase64(gr,"test.gif","application/gif",base64String );
gs.info("attachment_sys_id"+attachment_sys_id);
//Note: GlideSysAttachment這個對象只能適用於Scope範圍,Global不識別。

*19.Catelog Item的client script 獲取URL參數

function onLoad() {
   var requestBy = getParameterValue("id");//id 爲querystring的key
}

function getParameterValue(name) {  
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");  
    var regexS = "[\\?&]" + name + "=([^&#]*)";  
    var regex = new RegExp(regexS);  
    var results = regex.exec(unescape(top.location));  
    if (results == null) {  
        return "";  
    } else {  
        return unescape(results[1]);  
    }  
//使用console.log去觀察top這個對象會有驚喜。

*20.UI Action打開模態對話框

function openPopUp(){
    var dialogClass = window.GlideModal ? GlideModal : GlideDialogWindow;
    var dialog = new dialogClass("contract_renew_popup");
    dialog.setWidth("800");
    dialog.setTitle(getMessage("Renew The Contract"));
    dialog.setPreference("sys_id", g_form.getUniqueValue());
    dialog.setPreference("short_text", "Please verify or update the conditions of this contract renewal:");
    dialog.render(); //Open the dialog
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章