> For the complete documentation index, see [llms.txt](https://cortex-docs.paloaltonetworks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cortex-docs.paloaltonetworks.com/cortex-xsoar-8-on-prem/8.14/configure-cortex-xsoar/incident-configuration/incident-customization/create-an-incident-field/incident-field-trigger-scripts.md).

# Incident field trigger scripts

Incident fields can be associated with trigger scripts that check for field change conditions and take actions based on the change. These scripts can perform any action, such as dynamically changing the field value, notifying the responder when an incident severity has been changed, or when the conditions are met. For example, the **`ChangeRemediationSLAOnSevChange`** script changes the Remediation SLA of an incident, if the severity of an incident changes for any reason.

Scripts can be created in Python, PowerShell, or JavaScript on the **Scripts** page. To use a field trigger script, you need to add the **field-change-triggered** tag when creating the script. You can then add the script in the **Attributes** tab, when you edit or create an incident field. If you did not add the tag when creating the script, it cannot be selected, until you add the tag.

Cortex XSOAR comes out-of-the-box with field change scripts in the **Scripts** page, such as:

* **ChangeRemediationSLAOnSevChange**: Changes the remediation SLA once a change in incident severity occurs.
* **emailFieldTriggered**: Sends an email to the incident owner when the selected field is triggered.
* **StopTimeToAssignOnOwnerChange**: Stops the Time to Assignment SLA field, as soon as an owner was assigned to an incident.

A common use case is to create a script that only allows automated changes by a playbook not manual changes by a user.

```programlisting
args = demisto.args()
user = args["user"]
if user:
    demisto.executeCommand("setIncident", {args["cliName"]: args["old"]})
```

The script checks who made the change using the `user` field. The **cliName** argument returns the field name, so that it can be attached to multiple incident fields, and block changes to them, without the need to have a different script for each field.

If you want the script to change the incident name field and context data, run the following command:

```programlisting
execute_command("setIncident", {"name": incident_name, "id": incident_id})
```

<details>

<summary>Incident field trigger script arguments</summary>

Incident field trigger scripts have the following triggered field information available as arguments (args):

| Argument          | Description                                                                                                              |
| ----------------- | ------------------------------------------------------------------------------------------------------------------------ |
| `associatedToAll` | <p>Whether the field is associated with all or some incidents.</p><p>Value: <code>true</code> or <code>false</code>.</p> |
| `associatedTypes` | An array of the incident types, with which the field is associated.                                                      |
| `cliName`         | The name of the field when called from the command line.                                                                 |
| `description`     | The description of the field.                                                                                            |
| `isReadOnly`      | <p>Specifies whether the field is non-editable.</p><p>Value: <code>true</code> or <code>false</code>.</p>                |
| `name`            | The name of the field.                                                                                                   |
| `new`             | The new value of the field.                                                                                              |
| `old`             | The old value of the field.                                                                                              |
| `ownerOnly`       | <p>Specifies that only the creator of the field can edit.</p><p>Value: <code>true</code> or <code>false</code>.</p>      |
| `placeholder`     | The placeholder text.                                                                                                    |
| `required`        | <p>Specifies whether this is a mandatory field.</p><p>Value: <code>true</code> or <code>false</code>.</p>                |
| `selectValues`    | If this is a multi-select type field, these are the values the field can take.                                           |
| `system`          | Whether it is a Cortex XSOAR defined field.                                                                              |
| `type`            | The field type.                                                                                                          |
| `unmapped`        | Whether it is not mapped to any incident.                                                                                |
| `useAsKpi`        | Whether it is being used for tracking KPI on an incident page.                                                           |
| `user`            | The username of the user who triggered the script.                                                                       |
| `validationRegex` | Whether there is a regex associated for validation the values the field can hold.                                        |

Script limitations

* Trigger scripts can't close incidents.
* Post-processing scripts can modify an incident, but if a modified field has a trigger script, it is not called.
* Incident modifications executed within a trigger script are only saved to the database after the modifications are completed.

Best practices

* Fields that can hold a list (related incidents, multi-select/tag/role type custom fields) will provide an array of the delta. For example, if a multi-select field value has changed from \["a"] to \["a", "b"], the new argument of the script will get a value of \["b"].
* Incident field trigger scripts run as a batch. This means that if multiple incidents are changed in the same way and are set to trigger the same action, it will happen in one batch.
* When writing incident field trigger scripts, avoid scenarios that call the scripts endlessly (for example, a change in field A triggers script X, which changes field B's value, which in turn calls script Y, which changes field A's value).

</details>

<details>

<summary>Add an incident field trigger script to an incident field</summary>

After creating an incident field trigger script in the **Scripts** page in Python, PowerShell, or JavaScript, you can then associate it with an incident field.

1. Go to Settings & Info → Settings → Indicators → **Fields**.
2. Select the incident field and click **Edit**.
3. In the **Attributes** tab, under **Script to run when field value changes**, select the desired indicator field trigger script.

   <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><h4>Note</h4><p>Incident field trigger scripts must have the <strong><code>field-change-triggered</code></strong> tag to appear in the list.</p></div>

</details>

<details>

<summary>Field-change-triggered with Single Select or Multi Select types</summary>

1. Go to Settings & Info → Settings → Object Setup → Incident → **Incident Fields**.
2. Click **New** and create a new Incident field of one of the following types:
   * Single select
   * Multi-select
3. Click **Basic Settings** and in the **Values** section set the values you want to see in the incident layout dropdown list for this field.

   For example, `instance1_id,instance2_id,instance3_id,instance4_id,instance^,id`.
4. Click **Attributes** and in **Script to run when field value changes**, select the script.

   Example 9.

   This is an example of a single select script.

   ```programlisting
   # The custom mapping made for the field
   mapping_dict = {
       'instance1_id' : '123456',
       'instance2_id' : '12340987',
       'instance3_id' : '79874534',
       'instance4_id' : '90927834',
       'instance5_id' : '4543452',
   }    
       
   val = demisto.args()['new'] # when the script will be triggered this field will hold the new value chosen by the user.
   mapped_val = mapping_dict.get(val, val)  # getting the value from the map.
   execute_command('setIncident', {'customFields' :{'Single_select_field_example': mapped_val}}) # set the new incident mapped field
   ```

   Example 10.

   This is an example of a multi-select script.

   ```programlisting
   mapping_dict = {    
       'low' : '1',
       'medium' : '2',
       'high' : '3',
       'critical' : '4',
   }
       
   vals = argToList(demisto.args()['new']) # The new value from the user.
   mapped_list = [mapping_dict.get(v, v) for v in vals]
   execute_command('setIncident', {'customFields' : {'multi_select_field_example': mapped_list}})
   ```

   <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><h4>Note</h4><ul><li>When creating the script, in the <strong>Tags</strong> section, type <strong>field-change-triggered</strong>.</li><li>Choose the name of your custom fields to replace ‘Single_select_field_example’ or ‘multi_select_field_example’ in the examples above.</li></ul></div>
5. Go to Settings & Info → **Settings** → Object Setup → **Incidents** → **Layouts** and add the new incident field to an existing layout or create a new layout.
6. In the incident layout edit page, click **Fields and Buttons** and drag the new incident field you created to the layout.
7. Save the version.

   In the layout display, you will see the values you set in step 3.

   ![new-section.png](/files/P7l0bKpYUukM0XvAHni2)
8. Select one of the values. The layout will update with the mapped value as set on the script related to the incident field.

</details>

<details>

<summary>Use scripts with a grid field</summary>

You can use scripts to manipulate and populate data in the Grid field. In this example, you want analysts who can add comments for the incident during their shift and use a script to automatically populate the Date Logged column with the current date when a user adds a new row to the grid.

1. Create a script called `ShiftSummariesChange`. The script operates in the following phases:
   * The script gets all new rows and sets the Date Logged field to now (current day).
   * For each existing row, if the name matches, and the findings column is not updated, the Date Logged column is also updated.
   * After creating a grid field, it is saved with the new values using the `setIncident` command.

     ```programlisting
     var newField = args.new ? JSON.parse(args.new)  : [];
     //if line(s) added, set "datelogged" to now.
     if (oldField.length < newField.length) {
         // for each new line change date.    
         for(var i=oldField.length; i < newField.length; i++) {
             newField[i].datelogged = new Date ().toISOString();
         }
     }
     var columnName = "findings";
     // for each old line if the "columnName" has changed, change date to now.
     for(var i=0; i < oldField.length; i++) {
         if (newField[i] && oldField[i].fullname === newField[i].fullname &&
         oldField[i][columnName] !== newField[i][columnName]) {
             newField[i].datelogged = new Date().toISOString();
         }
     }
     var newVal = {};
     newVal[args.cliName] = newField;
     executeCommand("setIncident", newVal);
     ```
2. Add the **`field-change-triggered`** tag and save the script.
3. Create a Shift Summaries Grid field with the following columns:

   * Full name
   * Findings
   * Status
   * Date Logged

     Select **Date picker** with the **Lock** checkbox, so the script can populate the values for that column. If a column is unlocked (default), the column values can be entered manually (by users), or by a script.

   <div data-gb-custom-block data-tag="hint" data-style="info" class="hint hint-info"><h4>Note</h4><p>Ensure that <strong>User can add rows</strong> is selected.</p></div>
4. Add the grid field to a layout, which is attached to an incident type.

Add a row to a grid

During playbook execution, if a malicious finding is discovered you may want to add that finding to a grid. You can use a script in the playbook to add a new row to the grid with the malicious finding.

This is a Python script, which requires two arguments:

* `fieldCliName`: The machine name for the field for which you want to add a new row.
* `Row`: The new row to add the grid. This is a JSON object in lowercase characters, with no white space.

```programlisting
fieldCliName = demisto.args().get('field')
currentValue = demisto.incidents()[0]["CustomFields"][fieldCliName];

if currentValue is None:
    currentValue = [json.loads(demisto.args().get('row'))]
else:
    currentValue.append(json.loads(demisto.args().get('row')))

val = json.dumps({ fieldCliName: currentValue })
demisto.results(demisto.executeCommand("setIncident", { 'customFields': val }))
```

</details>

<details>

<summary>Incident field changes using SLA scripts</summary>

You can create scripts that perform specific actions when the SLA is breached in an incident field. For example, you can use the **SendEmailOnSLABreach** script that sends an email to specific users when the script is triggered. For more information, see [Automate changes to incident fields using SLA scripts](/cortex-xsoar-8-on-prem/8.14/configure-cortex-xsoar/slas/automate-changes-to-incident-fields-using-sla-scripts.md).

</details>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://cortex-docs.paloaltonetworks.com/cortex-xsoar-8-on-prem/8.14/configure-cortex-xsoar/incident-configuration/incident-customization/create-an-incident-field/incident-field-trigger-scripts.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
