Skip to Content

Populate Fields on Insert

Automatically populate fields with default values or calculated values when a record is created.

Table: incident When: before
#auto-populate #default-values #insert #before #initialization

Script Code

JavaScript
1(function executeRule(current, previous /*null when async*/) {
2
3  // Only run on new records
4  if (!current.isNewRecord()) {
5    return;
6  }
7
8  // Example 1: Set default priority based on caller's VIP status
9  if (current.caller_id.vip.toString() === 'true' && current.isNil('priority')) {
10    current.priority = '2';  // High priority for VIPs
11    current.work_notes = 'Priority set to High due to VIP caller';
12  }
13
14  // Example 2: Auto-populate due date based on priority
15  if (!current.isNil('priority') && current.isNil('due_date')) {
16    var priorityToDueDays = {
17      '1': 4,    // Critical: 4 hours
18      '2': 8,    // High: 8 hours
19      '3': 24,   // Moderate: 24 hours
20      '4': 72,   // Low: 72 hours
21      '5': 120   // Planning: 120 hours
22    };
23
24    var hoursToAdd = priorityToDueDays[current.priority.toString()] || 24;
25    var gdt = new GlideDateTime();
26    gdt.addHours(hoursToAdd);
27    current.due_date = gdt;
28
29    gs.info('Set due date to ' + gdt.getDisplayValue() + ' for priority ' + current.priority);
30  }
31
32  // Example 3: Set category based on configuration item
33  if (!current.cmdb_ci.nil() && current.isNil('category')) {
34    var ciClass = current.cmdb_ci.sys_class_name.toString();
35
36    var classToCategory = {
37      'cmdb_ci_computer': 'hardware',
38      'cmdb_ci_server': 'hardware',
39      'cmdb_ci_app_software': 'software',
40      'cmdb_ci_database': 'database',
41      'cmdb_ci_network_adapter': 'network'
42    };
43
44    if (classToCategory[ciClass]) {
45      current.category = classToCategory[ciClass];
46      current.work_notes = 'Category auto-populated based on CI type: ' + ciClass;
47    }
48  }
49
50  // Example 4: Copy location from caller if not set
51  if (!current.caller_id.nil() && current.isNil('location')) {
52    current.location = current.caller_id.location;
53  }
54
55  // Example 5: Generate unique reference number
56  if (current.isNil('u_reference_number')) {
57    var prefix = 'REF';
58    var timestamp = new GlideDateTime().getNumericValue();
59    current.u_reference_number = prefix + '-' + timestamp.toString().substring(8);
60  }
61
62})(current, previous);

How to Use

1. Create a before Business Rule on your table 2. Check "Insert" checkbox only 3. Customize the field population logic for your needs 4. Test by creating new records

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts