Transform Scripts
Transform Scripts in ServiceNow are powerful scripting mechanisms used during the data import process to manipulate and control how data is transformed from a staging table (import set table) into a target table. They are a critical component of the Import Set framework, which is used to bring exte… Transform Scripts in ServiceNow are powerful scripting mechanisms used during the data import process to manipulate and control how data is transformed from a staging table (import set table) into a target table. They are a critical component of the Import Set framework, which is used to bring external data into ServiceNow. Transform Scripts run during the execution of a Transform Map and allow developers to apply custom logic at various stages of the transformation process. They provide granular control over how each record or the entire dataset is processed. There are two primary types of Transform Scripts based on when they execute: 1. **onStart** – Runs once before any records are transformed. This is useful for initializing variables, setting up counters, or performing pre-processing tasks like clearing existing data before new data is imported. 2. **onComplete** – Runs once after all records have been transformed. This is commonly used for cleanup tasks, logging summaries, sending notifications, or triggering follow-up processes. 3. **onBefore** – Runs before each individual record is transformed. Developers can use this to validate data, set default values, skip records based on conditions, or manipulate source values before they are mapped to the target. 4. **onAfter** – Runs after each individual record is transformed. This is useful for creating related records, updating additional fields, or performing post-insert logic on the target record. 5. **onForeignInsert** – Runs when a reference field requires the creation of a new record in a referenced table. Within Transform Scripts, developers have access to key objects such as `source` (the import set row), `target` (the target table record), `map` (the transform map), `log` (for logging), and `action` (to determine insert/update behavior or skip records using `ignore`). Transform Scripts are essential for handling complex transformation requirements that cannot be achieved through simple field mapping alone, enabling developers to integrate external data seamlessly into ServiceNow while maintaining data integrity and business logic compliance.
Transform Scripts in ServiceNow – Complete Guide for CAD Exam
Transform Scripts in ServiceNow
Why Transform Scripts Are Important
When importing data from external sources into ServiceNow, the data rarely arrives in a format that perfectly matches the target table structure. Transform Scripts provide a powerful mechanism to manipulate, validate, cleanse, and transform data during the import process. Without Transform Scripts, administrators and developers would need to manually correct data inconsistencies after import, which is time-consuming, error-prone, and inefficient. Transform Scripts ensure data integrity, automate complex mappings, and allow sophisticated logic to be applied during the ETL (Extract, Transform, Load) process.
What Are Transform Scripts?
Transform Scripts are server-side JavaScript scripts that execute during the transformation phase of a data import in ServiceNow. They are associated with a Transform Map and allow developers to apply custom logic that goes beyond what simple field mapping can achieve. Transform Scripts can run at different points during the transformation process, giving developers fine-grained control over how each row of imported data is processed.
Transform Scripts are configured within the Transform Map record and are part of the broader Import Set framework, which includes:
- Data Sources – Define where external data comes from (files, JDBC, LDAP, etc.)
- Import Set Tables – Staging tables where imported data is temporarily stored
- Transform Maps – Define how data moves from the staging table to the target table
- Transform Scripts – Custom logic applied during transformation
How Transform Scripts Work
Transform Scripts operate within the context of a Transform Map and execute at specific events during the transformation of each row. There are several key event types:
1. onStart
This script runs once before the transformation begins processing any rows. It is useful for initializing variables, setting up lookup tables, or performing pre-processing tasks.
Example use case: Initialize a counter variable to track how many records are created vs. updated.
2. onBefore
This script runs before each row is transformed and inserted/updated in the target table. It allows you to manipulate the source or target values before the record is saved. You can also use it to skip rows by setting ignore = true.
Key objects available:
- source – Represents the current row in the import set (staging) table
- target – Represents the record being created or updated in the target table
- map – The transform map record
- log – For logging messages
- ignore – A boolean; set to true to skip the current row
- action – Indicates the action being taken (insert, update, ignore)
Example: if (source.u_status == 'inactive') { ignore = true; }
3. onAfter
This script runs after each row has been transformed and the target record has been saved. It is useful for post-processing tasks such as creating related records, updating reference fields, or triggering additional workflows.
Key objects available are the same as onBefore, plus the target record now has a sys_id since it has been saved.
Example use case: After importing a user record, create a default role assignment for that user.
4. onComplete
This script runs once after all rows have been processed. It is useful for cleanup tasks, sending summary notifications, or generating reports about the import.
Example use case: Send an email notification summarizing how many records were imported, updated, or skipped.
5. onChoiceCreate
This script runs when a choice value is encountered that does not exist in the target choice list. It allows you to control whether the new choice value should be created or handled differently.
6. onForeignInsert
This script runs when a reference field value does not match an existing record in the referenced table and a new record would need to be created. It allows you to control the creation of referenced records during import.
Key Concepts to Understand
The source and target Objects:
The source object refers to the current row in the import set table (staging table). The target object refers to the record in the destination/target table. In onBefore scripts, you can modify target field values before they are saved. In onAfter scripts, the target record has already been committed to the database.
The ignore Variable:
Setting ignore = true in an onBefore script causes the current row to be skipped entirely. The record will not be inserted or updated in the target table. This is extremely useful for filtering out unwanted data during import.
The action Variable:
The action variable tells you what operation is being performed: insert, update, or ignore. You can also set the action to control behavior programmatically.
Coalesce Fields:
While not a Transform Script concept per se, coalesce fields on field maps determine whether a record should be inserted as new or updated if it already exists. Transform Scripts often work in conjunction with coalesce logic.
Execution Order:
1. onStart (once)
2. For each row: Field Mapping → onBefore → Record Save → onAfter
3. onComplete (once)
Understanding this execution order is critical for placing your logic in the correct event.
Practical Examples
Example 1 – Setting a default value in onBefore:
If the source data does not include a priority value, you can set a default in the onBefore script:
if (source.u_priority == '') { target.priority = 3; }
Example 2 – Concatenating fields in onBefore:
target.short_description = source.u_category + ' - ' + source.u_summary;
Example 3 – Creating related records in onAfter:
After a user is imported, you could create a default group membership record using the target's sys_id.
Example 4 – Skipping rows in onBefore:
if (source.u_department == 'ARCHIVED') { ignore = true; }
Transform Scripts vs. Other Mapping Options
ServiceNow provides several mapping options within Transform Maps:
- Direct field mapping – Simple one-to-one mapping between source and target fields
- Mapping with coalesce – Used to match existing records for updates
- Choice action – Controls behavior when encountering new choice values
- Transform Scripts – For complex logic that cannot be achieved with simple mapping
Transform Scripts should be used when the built-in mapping capabilities are insufficient for your requirements.
Best Practices
- Use onBefore for data manipulation and validation before the record is saved
- Use onAfter for creating related records or performing actions that require the target record's sys_id
- Use onStart and onComplete for initialization and cleanup tasks respectively
- Always test Transform Scripts with a small dataset before running a full import
- Use the log object for debugging: log.info('Processing: ' + source.u_name);
- Be mindful of performance – complex scripts in onBefore/onAfter run for every row
- Set ignore = true to skip records that do not meet your criteria rather than letting bad data enter the system
Exam Tips: Answering Questions on Transform Scripts
1. Know the Event Types and When They Fire:
The most commonly tested concept is understanding when each event type executes. Remember: onStart fires once before processing, onBefore fires before each row is saved, onAfter fires after each row is saved, and onComplete fires once after all rows are processed. If a question asks where to place logic that needs a sys_id from the newly created target record, the answer is onAfter.
2. Understand the source and target Objects:
Questions may test whether you know the difference. The source object always refers to the import set (staging) table row, and the target object refers to the destination table record. If a question references reading values from the imported data, use source. If it references setting values on the destination record, use target.
3. Remember the ignore Variable:
If a question asks how to skip or prevent certain rows from being imported, the answer involves setting ignore = true in an onBefore Transform Script. This is a very commonly tested concept.
4. Differentiate Between Transform Scripts and Field Maps:
Simple one-to-one mappings are handled by field maps on the Transform Map. Transform Scripts are for complex logic. If a question describes a simple mapping scenario, the answer is likely a field map, not a Transform Script.
5. Understand the Import Set Framework Holistically:
Questions may test your understanding of the entire data import pipeline. Know the sequence: Data Source → Import Set Table → Transform Map (with Field Maps and Transform Scripts) → Target Table. Transform Scripts are just one piece of this pipeline.
6. Watch for Keyword Clues in Questions:
- "before the record is inserted" → onBefore
- "after the record is saved" or "needs the sys_id" → onAfter
- "skip the record" or "do not import" → ignore = true in onBefore
- "initialize" or "before any records are processed" → onStart
- "summary" or "after all records" → onComplete
7. Performance Considerations:
If a question mentions performance concerns with large data imports, remember that onBefore and onAfter scripts execute per row. Minimize database queries within these scripts, and use onStart to cache lookup data when possible.
8. Coalesce vs. Transform Scripts:
Coalesce determines whether to insert or update. Transform Scripts add custom logic. These are different concepts and exam questions may try to confuse the two. Coalesce is configured on the field map, not in a Transform Script.
9. Common Pitfall Questions:
Be aware that modifying the target object in an onAfter script does not automatically save those changes because the record has already been saved. You would need to explicitly call target.update() in an onAfter script for changes to persist, though this is generally not recommended as it triggers business rules again.
10. Practice Scenario-Based Questions:
Many CAD exam questions present a scenario and ask you to choose the best approach. When the scenario involves data import with custom logic requirements, evaluate whether the requirement can be met with simple field mapping first. Only choose Transform Scripts when the logic requires conditional processing, data manipulation, or record skipping that cannot be accomplished through standard mapping.
🎓 Unlock Premium Access
ServiceNow Certified Application Developer + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 3305 Superior-grade ServiceNow Certified Application Developer practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- CAD: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!