# Modified Java Script Value

The **Modified Java Script Value** step provides a user interface for building JavaScript expressions you can use to create or modify fields.

The script you write runs **once per incoming row**.

{% hint style="info" %}
This step is not an input step and cannot run without an incoming row stream.

This step is a modified version of the **JavaScript Values** step, which has been deprecated and removed from PDI.
{% endhint %}

### Step name

**Step name** specifies the unique name of the step on the canvas. You can change it.

### User interface overview

![Modified Java Script Value dialog](/files/R7RnvQAP1TEOf5jE02ha)

The step includes:

* A **Java script functions** pane (left)
* A **Java script** pane (right)
* A **Fields** table (bottom)

### Java script functions pane

The **Java script functions** pane includes:

* **Transform Scripts**: script tabs you created in this step.
* **Transform Constants**: predefined constants that control row handling.
* **Transform Functions**: built-in helper functions (implemented in Java) with sample scripts.
* **Input Fields**: fields available from upstream steps.
* **Output Fields**: fields created or modified by your script.

#### Transform Constants and `trans_Status`

Use `trans_Status` to control what happens to each row.

{% hint style="warning" %}
To use these constants reliably, set `trans_Status = CONTINUE_TRANSFORMATION` at the beginning of your transform script, so the assignment is applied to the first row.
{% endhint %}

Constants:

* `CONTINUE_TRANSFORMATION`: includes the current row in the output.
* `SKIP_TRANSFORMATION`: excludes the current row and continues processing.
* `ERROR_TRANSFORMATION`: excludes the current row, raises an error, and stops processing.
* `ABORT_TRANSFORMATION`: excludes the current row and stops processing **without** raising an error.

### Java script pane

The **Java script** pane is where you write your code.

You can insert constants, functions, and fields by double-clicking items in the left pane or dragging and dropping them into the script.

| Setting                | Description                                                                                                                                                                                                                                                                                    |
| ---------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Position**           | Displays the current cursor line/position.                                                                                                                                                                                                                                                     |
| **Compatibility mode** | Uses version `2.5` of the JavaScript engine. When cleared (default), the step uses engine version `3`. In the 2.5 engine, value objects are directly modifiable and their type can be changed (for example, you can convert a date variable into a string). PDI uses the Mozilla Rhino engine. |
| **Optimization level** | JavaScript optimization level. `-1` runs interpreted. `0` performs no optimizations. `1-9` enables optimizations (default `9`, fastest execution but slower compilation).                                                                                                                      |

#### Script types (tabs)

You can create and manage multiple scripts in one step.

![Modified Java Script Value step Script Types dialog](/files/2dRJAjo5sRm2qXSHlRMS)

Right-click a script tab to manage its type:

* **Add new**: add a new script tab.
* **Add copy**: duplicate the current script into a new tab.
* **Set Transform Script**: script executed for each incoming row (one tab only).
* **Set Start Script**: script executed before processing the first row.
* **Set End Script**: script executed after the last row is processed.
* **Remove Script Type**: disables execution for that script tab (does not delete the tab).

To rename a script tab, rename it under **Transform Scripts** in the left pane.

### Fields table

The **Fields** table lists variables from your script and lets you define output metadata.

{% hint style="info" %}
JavaScript variables are not the same as PDI variables.
{% endhint %}

| Field                                        | Description                                                               |
| -------------------------------------------- | ------------------------------------------------------------------------- |
| **Fieldname**                                | Input field name.                                                         |
| **Rename to**                                | New field name (when renaming) or the target field name (when replacing). |
| **Type**                                     | Output data type.                                                         |
| **Length**                                   | Output length.                                                            |
| **Precision**                                | Output precision.                                                         |
| **Replace value ‘Fieldname’ or ‘Rename to’** | `Y` replaces a field value. `N` renames a field.                          |
| **Get variables**                            | Retrieves JavaScript variables from your script.                          |
| **Test Script**                              | Tests script syntax and opens the Generate Rows dialog for test data.     |

#### Replace an input field value

To replace an existing field’s value, enter the field in **Rename to** and set **Replace value ‘Fieldname’ or ‘Rename to’** to `Y`.

The step uses **Rename to** (or **Fieldname** when **Rename to** is blank) to look up the existing field and replace its value and metadata.

If the specified field does not exist in the input stream, the step outputs an error indicating the field could not be found.

Example (with **Compatibility mode** selected):

```javascript
field1.setValue(100);
```

{% hint style="info" %}
`setValue()` accepts all PDI-compatible types.
{% endhint %}

### Internal API objects

The step exposes internal API objects you can use in scripts:

* `_TransformationName_`: transformation name (String)
* `_step_`: step instance (`org.pentaho.di.trans.steps.scriptvalues_mod.ScriptValuesMod`)
* `rowMeta`: row metadata (`org.pentaho.di.core.row.RowMeta`)
* `row`: the current row (`Object[]`)

### Tips and examples

#### Check whether a field exists

```javascript
var idx = getInputRowMeta().indexOfValue("lookup");
if ( idx < 0 )
{
   var lookupValue = 0;
}
else
{
   var lookupValue = row[idx];
}
```

With **Compatibility mode** selected:

```javascript
var idx = row.searchValueIndex("lookup");
if ( idx < 0 )
{
   var lookupValue = 0;
}
else
{
   var lookupValue = row.getValue(idx);
}
```

{% hint style="warning" %}
All rows flowing over a single hop must have the same number of fields and compatible field names/types.
{% endhint %}

#### Add a new field

Fields must be added in a consistent order to keep row structure coherent.

To add a field:

1. Define it as a `var` in the script.
2. Add it to the **Fields** table.

#### Use NVL to replace null

With **Compatibility mode** selected:

```javascript
var a;
if ( fieldname.isNull() )
{
    a = '0';
}
else
{
    a = fieldName.getString();
}
```

You can also use:

```javascript
fieldName.nvl('1');
```

#### Split a mixed numeric/string field

With **Compatibility mode** selected:

```javascript
java;

var str = Merchant_Code.getString();

var code = "";
var name = "";

for (i = 0; i < str.length(); i++ )
{
    c = str.charAt(i);
    if ( ! java.lang.Character.isDigit(c) )
    {
        code = str.substring(0, i);
        name = str.substring(i);
        Alert("code="+code+", name="+name);
        break;
    }
}
```

#### Compare values (strings and numerics)

Values are Java objects, so comparison using `=`, `>`, and `<` can fail for some types.

**String comparison**

```javascript
string.equals(otherString)
```

Do not use `==` for strings.

Ignore case:

```javascript
string.equalsIgnoreCase(otherString)
```

**Numeric comparison and `switch`**

If values you expect to be integers behave like floating-point values, use:

```javascript
parseInt(num) == parseInt(num2)
```

Or:

```javascript
switch(parseInt(valuename))
{
case 1:
case 2:
case 3:
 strvalueswitch = "one, two, three";
 break;
case 4:
 strvalueswitch = "four";
 break;
default:
 strvalueswitch = "five";
}
```

#### Filter rows

Set `trans_Status` to control whether a row is output.

```javascript
trans_Status = CONTINUE_TRANSFORMATION
if (/* condition */) trans_Status = SKIP_TRANSFORMATION
```

### Sample transformations

The `design-tools/data-integration/samples/transformations` directory includes example transformations demonstrating this step:

* JavaScript - Access database connection metadata
* JavaScript - Access environment variables
* JavaScript - Add 2 and a half seconds to a Date
* JavaScript - Base64 Decoder and Encoder
* JavaScript - create new rows
* JavaScript - date to string conversion
* JavaScript - dialog
* JavaScript - extract date from filename
* JavaScript - Get the filename from a path
* JavaScript - Hex to Integer conversion
* JavaScript - parse Debet-Credit prefix in numbers
* JavaScript - Parse XML
* JavaScript - process all fields per row
* JavaScript - replace values in a string with other values
* JavaScript - Skip rows after x rows
* JavaScript - Split String
* JavaScript - String to Number to String conversion
* JavaScript - Strip line feeds from text
* JavaScript - truncate a date


---

# Agent Instructions: 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:

```
GET https://docs.pentaho.com/pdia-data-integration/pdi-transformation-steps-reference-overview/modified-java-script-value.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
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.
