# Actions

> How action components collect input from users and run a Kex write script, including the generator templates, variable types and script conventions.

An action component (*Handling*, configured on the workspace tab **Actions**, *Handlingar*) is a small form that runs a Kex script. It consists of **variables**, which the user fills in, and a **script**, which runs with those values when the user presses the run button. Typical actions add a new dimension value together with its first data, remove rows, or move values between dimension values.

Actions are shown to end users in the sidebar of the workspace, as vertical tabs along the right edge. They can also be placed in the layout with a `LayoutableAction` component (see [Workspaces and components](components.html#layoutable-action)).

```flow
User | fills in variables -> Action component | @Variables bound to input -> Kex write script | write insert / replacement / update -> Value types and dimensions | data changed, calculations follow
```

## Action settings

| Setting | Swedish label | Configuration | Meaning |
|---|---|---|---|
| Name | *Namn* | `Name` | title of the action |
| Description | *Beskrivning* | `Description` | help text shown with the form |
| Run button label | *Knappetikett* | `RunButtonLabel` | text on the button; optional |
| Show in sidebar | *Visa i sidofält* | `HideInSidebar` (inverted) | whether the action is listed in the sidebar |
| Variables | *Variabler* | `VariableInputs` | the input fields |
| Script | *Skript* | `Script` | the Kex script |

Action names must be unique within the workspace. Older configurations that contain duplicate names are given unique names when read.

### Groups

Actions can be collected in an **action group** (`ActionComponentGroup`), which shows them under a common heading in the sidebar. A group has only an ID, a name and a description. It has no logic of its own. Actions can also be placed directly on the workspace without a group.

## The generator

Actions are rarely written from scratch. **Create → Component** (*Skapa → Komponent*) opens **Generate action component** (*Generera åtgärdskomponent*) with three templates:

| Template | Swedish label | Generates |
|---|---|---|
| Add | *Lägg till* | creates new dimension values and writes initial data |
| Remove | *Ta bort* | removes rows from selected value types |
| Custom action | *Anpassad åtgärd* | an empty component; you write the script yourself |

For *Add* and *Remove*, the wizard first asks for the **value types** that rows should be added to or removed from. It then shows **one tab per dimension** of the selected value types. For each dimension, choose a type (*TYP*):

| Type | Swedish label | Effect |
|---|---|---|
| New | *Ny* | the action creates a new dimension value |
| Existing | *Befintlig* | the user selects an existing value; becomes a `Dimension` variable |
| Fixed | *Fixed* | a hard-coded value; no input |

A dimension set to **New** opens two further choices:

- which **properties** the user should fill in for the new value, each again as New, Existing or Fixed;
- the toggle **Require code for new dimension value** (*Krav på kod till nytt dimensionsvärde*). When it is off, the code is derived from the name with `makecode`.

The generator produces both the variable list and the script. Both remain **fully editable** afterwards: the script field is a normal Kex editor with a validity indicator. A generated script is a starting point, not a locked template.

### Example: Add

*Add* on the value type `Amount`, with `Project` as New (including the property `Region`) and `Department` as Existing, produces the variables `@Project.Name` (text, format Name), `@Project.Region` (property), `@Department` (dimension) and `@Amount.Value` (numeric), and a script of this shape:

```kex
scalar [Project.Code] = makecode(@Project.Name) within (Project)
if any (Project == [Project.Code]) {
  fatal `Project '{[Project.Code]}' already exists.`
}

write insert to Project <- Project = [Project.Code], $name = @Project.Name,
     [.Region] = @Project.Region
write insert to Amount <- @Amount.Value, Project = [Project.Code], Department = @Department
```

The script derives a code from the entered name, stops with an error message if a project with that code already exists, then creates the dimension value with its property and writes the first value. The exact generated text depends on the model.

### Example: Remove

*Remove* on the same value type produces:

```kex
write replacement to Amount <-
Amount.*

exclude calculated

where not (Project in @Project && Department in @Department)
```

How to read it:

- **Removal is written as a rewrite.** `write replacement` replaces the contents of `Amount` with the result of the query, and the query is "all of `Amount` except the selected combination" (`where not (…)`). Rows that are not in the result are deleted.
- **`exclude calculated`** leaves calculated rows out of the query, so the replacement only concerns data entered by users or imported. Calculated rows are neither rewritten nor deleted by the action. They are maintained by their calculations.
- **`in` instead of `==`**, because the variables can be multi-select. With `Multiple` on, `@Project` can hold several projects, and the action removes all of them in one run.

See [Kex](kex.html#write-variants) for the write variants and how they behave inside and outside calculations.

The generator uses `exclude calculated`, `makecode(…) within (…)`, `if any (…) { … }` and `` fatal `…` ``. They are described under [Control flow and messages](kex.html#control-flow-and-messages) and [makecode](kex.html#makecode).

## Variables

Variables are the form fields of the action. The script refers to a variable as `@Identifier`.

| Variable type | Swedish label | Configuration | Value |
|---|---|---|---|
| Text | *Textvariabel* | `Text` | a string |
| Numeric | *Numerisk variabel* | `Numeric` | a number |
| Dimension | *Dimensionsvariabel* | `Dimension` | one or more values of a dimension |
| Property | *Egenskapsvariabel* | `Property` | one or more values of a dimension property |

All variables have an **identifier**, a **name** (the field label) and an optional **description**.

### Text variables

| Setting | Swedish label | Values |
|---|---|---|
| `Format` | *Format* | `Code` (*Kod*): validated as a dimension-value code · `Name` (*Namn*): validated as a dimension-value name · `FreeText` (*Fritt text*): any text |
| `MaxLength` | *Max antal tecken* | maximum number of characters |
| `Pattern` | *Mönster* | a regular expression the input must match |

### Numeric variables

| Setting | Values |
|---|---|
| `FormatCode` | `Number` or `Percent` |
| `Min`, `Max` | allowed range; optional |

### Dimension and property variables

| Setting | Swedish label | Meaning |
|---|---|---|
| `DimensionId` | *Dimension* | the dimension to choose from |
| `PropertyId` | *Egenskap* | property variables only: the property to choose from |
| `Multiple` | *Flera* | allow several values; use `in` in the script |
| `SortBy`, `SortingMethod` | | sort order in the picker |
| `DisplayFormatId` | *Visa som* | display format in the picker |
| `AccessListId` | *Behörighetslista* | limits the selectable values to those the user may access under the list |
| `Condition` | *Sätt filter* (funnel icon) | a Kex condition limiting the selectable values, edited in the same guided/Kex panel as the [value type condition](datasets.html#value-type-condition) |

!!! tip "Save before setting a variable filter"
    The *Set filter* panel on a variable stays empty until the action has been saved once. Create the variables, save the action, and then configure the filters.

## The script

The script is ordinary Kex, usually with one or more `write` statements. See [Kex](kex.html). A few conventions:

- Refer to inputs with `@Identifier`. Generated identifiers follow the pattern `@<Dimension>` for existing values, `@<Dimension>.Name` for a new value's name, `@<Dimension>.<Property>` for properties, and `@<ValueType>.Value` for the numeric input.
- Use `write insert` for "create if not present", `write update` to change existing rows only, and `write replacement` with `where not` to remove.
- Validate with guard clauses (`if any (…) { fatal … }`) so that the user gets a clear message instead of a partial write.
- Calculations that read the changed value types run automatically after the action, like after any other data change. See [Calculations](calculations.html).

In the configuration, the script is stored in an **attribute** (`Script="…"`), not in an element. This is deliberate: it keeps line breaks and indentation intact.

!!! warning "Actions change data directly"
    An action runs a write script against the plan when the user presses the button. Test new actions in a copy of the plan or on test dimension values, and prefer `write insert` and guarded scripts over broad `replacement` writes.

An action is **not part of the grid's undo history**: after it has run, no *Ångra* (undo) button appears. To reverse an action, run a counter-action or edit the values.

## Legacy action components

Configurations from older versions can contain `LegacyActionComponents`, a declarative predecessor (add, remove, change property value, move or copy plan data). In v2 plans they are removed when the configuration is read. Their content is not converted. Rebuild such actions with the generator.

!!! agent "Pitfalls for agents"
    See the [Agent guide](agent-pitfalls.html#actions) for pitfalls when generating or editing action scripts.

## Related

- [Kex](kex.html)
- [Workspaces and components](components.html)
- [Using apps](end-user.html)
- [App configuration (XML/JSON)](app-config.html)
