---
url: https://script-ui.runio.dev/tutorials/change-data.md
---
# 2. A tool that changes data

A tool that only shows data cannot do much harm. One that refunds orders can. This tutorial walks through two tools of the demo: one that asks before it acts, and one that checks what was typed.

The demo is not part of the Composer package. It runs from a copy of the repository:

```bash
git clone https://github.com/RunIO-dev/runio-script-ui.git
cd runio-script-ui
composer install
php bin/script-ui serve examples/tools
```

## Ask before you act

This is the whole refund tool. `$shop` stands in for your own code.

```php {16-20,24-29,33-40}
<?php
// Refund orders
// Find a customer's orders, tick the ones to refund, confirm.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, text, select, table, button, success, info, rerun};

$shop = Shop::open();

title('Refund orders');

$email = text('Customer email', placeholder: 'ava@example.com', help: 'Try ava@example.com or omar@example.com.');
$status = select('Status', ['paid', 'shipped']);

if ($email === '') {
    info('Type a customer email to see their orders.');

    return;
}

$orders = $shop->orders(email: $email, status: $status);

$picked = table(
    $orders,
    selectable: true,
    columns: ['id' => 'Order', 'created_at' => 'Placed on', 'items' => 'Items', 'total' => 'Total'],
    empty: 'No ' . $status . ' orders for ' . $email . '.',
);

$count = count($picked) === 1 ? '1 order' : count($picked) . ' orders';

if ($picked && button('Refund selected', style: 'danger', confirm: 'Refund ' . $count . '?')) {
    foreach ($picked as $order) {
        $shop->refund($order['id']);
    }

    success('Refunded ' . $count . '.');
    rerun();
}

```

**Lines 16 to 20: nothing to do yet.** Without an email there is nothing to show. An early `return` ends the page there.

**Lines 24 to 29: the table returns the ticked rows.** They come back exactly as you passed them in. The browser only says which rows are ticked, so `$order['id']` is an id of yours, never something that was typed into a request.

**Line 33: the button.** It is drawn only while something is ticked. `confirm:` makes it ask first, and the question names what will happen:

![The refund tool with two ticked orders. Under the red button "Refund selected" a question asks "Refund 2 orders?" with the buttons "Yes" and "Cancel".](https://script-ui.runio.dev/shots/refund.png){.shot}

`button()` returns `true` only after the user answered yes to exactly that question. When the selection changes in between, the question changes with it, and an old yes does not count.

**Lines 34 to 39: the work.** It runs once. `rerun()` then runs the script again, so that the table above shows the orders that are left. The message survives that:

![The refund tool after the yes: the message "Refunded 2 orders." and one order left in the table.](https://script-ui.runio.dev/shots/refund-done.png){.shot}

## Check what was typed

`field_error()` writes under an input what is wrong with it. `valid()` says whether anything was found wrong in this run.

```php {25-27,31-42,56-60}
<?php
// Give a coupon
// A form that checks what was typed, and says under each field what is wrong with it.

require_once __DIR__ . '/_shop.php';

use function Runio\ScriptUi\{title, heading, text, number, date_input, textarea, button, field_error, valid, success, table};

$shop = Shop::open();

title('Give a coupon');

$email = text('Customer email', placeholder: 'ava@example.com', help: 'Try ava@example.com or omar@example.com.');
$percent = number('Discount in percent', default: 10, min: 1, max: 50, step: 1);
$until = date_input('Valid until', default: date('Y-m-d', strtotime('+30 days')), min: date('Y-m-d'));
$reason = textarea('Reason', rows: 2, help: 'It goes to the log. More than 20 percent needs one.');

$customer = $shop->customer($email);
$coupons = $customer === null ? [] : $shop->coupons($customer['email']);

// Checked on every run: the note comes when the user leaves the field, and it
// stays until the field is right. An empty field is left alone here, or a new
// page would start full of red. The answer tells whoever may open this tool
// who is a customer. That is fine in a back office, and nowhere else.
if ($email !== '' && $customer === null) {
    field_error('Customer email', 'No customer has this email.');
}

if (button('Give coupon', style: 'primary')) {
    // Checked when the button is pressed: what is missing, and what only counts now.
    if ($email === '') {
        field_error('Customer email', 'Enter the email of a customer.');
    }
    if ($percent === null) {
        field_error('Discount in percent', 'Enter a discount from 1 to 50.');
    }
    if ($until === null) {
        field_error('Valid until', 'Choose the last day of the coupon.');
    }
    if ($percent > 20 && mb_strlen($reason) < 10) {
        field_error('Reason', 'More than 20 percent needs a reason. Write a sentence.');
    }
    // The form still holds what was typed after the coupon was given. A second
    // press, or a double click, must not give a second one. Two requests at the
    // very same moment would both pass this check: where it matters, let the
    // database refuse the second one, with a unique key.
    foreach ($coupons as $coupon) {
        if ($coupon['until'] >= date('Y-m-d')) {
            field_error('Customer email', $customer['name'] . ' has a coupon already: ' . $coupon['code'] . ', valid until ' . $coupon['until'] . '.');

            break;
        }
    }

    // field_error() does not stop the script. Nothing is done until all of it is right.
    if (valid()) {
        $code = $shop->addCoupon($customer['email'], $percent, $until);
        $coupons = $shop->coupons($customer['email']);
        success($customer['name'] . ' got ' . $percent . ' % off with the code ' . $code . ', until ' . $until . '.');
    }
}

if ($customer !== null) {
    heading('Coupons of ' . $customer['name']);
    table(
        $coupons,
        columns: ['code' => 'Code', 'percent' => 'Percent', 'until' => 'Valid until', 'given' => 'Given on'],
        empty: 'No coupon yet.',
    );
}

```

![The coupon tool after a press on "Give coupon": a red note under "Customer email" says "Enter the email of a customer.", and one under "Reason" says that more than 20 percent needs a reason.](https://script-ui.runio.dev/shots/coupon.png){.shot}

There are two places to check, and this tool uses both.

**On every run, lines 25 to 27.** The note comes as soon as the user leaves the field, and it stays until the field is right. An empty field is left alone there, or a new page would start full of red.

**Behind the button, lines 31 to 42.** What is missing is asked for when the button is pressed. The first field that is wrong gets the keyboard focus, and software that reads the page out says the note.

**Lines 56 to 60.** `field_error()` does not stop the script. Ask `valid()` before the work is done.

The comment above line 47 names something every such tool has to think of: the form still holds what was typed after the coupon was given, so a second press must not give a second one.

## Who pressed what

Colleagues will press buttons that change data. With `log:` every press and every download reaches a function of yours. This is the setting of the demo:

```php {17-26}
<?php

declare(strict_types=1);

/**
 * Settings for "script-ui serve examples/tools": the named arguments of Runio\ScriptUi\serve().
 *
 * There is no login check here, so the demo only answers on this computer.
 * On a real server you would add one:
 *
 *     'auth' => fn () => $_SESSION['admin_email'] ?? null,
 */

return [
    'name' => 'Shop back office',

    // Called for every button a user presses and every file a user downloads. Here: one JSON line per action.
    // It returns false when the line could not be written. A download is then not sent.
    'log' => static function (array $entry): bool {
        $file = __DIR__ . '/../var/audit.log';
        if (!is_dir(dirname($file))) {
            mkdir(dirname($file), 0777, true);
        }

        return file_put_contents($file, json_encode($entry, JSON_UNESCAPED_UNICODE) . "\n", FILE_APPEND | LOCK_EX) !== false;
    },
];

```

An entry says who it was, which tool and which button, whether a question was answered with yes, what every input held in that run, and what the page said was wrong. The demo shows its log in a tool of its own:

![The audit log of the demo: a table with the time, the user, the tool, the button and the inputs of every press.](https://script-ui.runio.dev/shots/audit.png){.shot}

## Rules for a tool that changes data

1. Change data only inside `if (button(...))`. The script also runs when somebody changes a filter.
2. Ask with `confirm:` before something that cannot be undone, and say in the question what will happen.
3. Check behind the button, and ask `valid()` before the work.
4. A button can be pressed twice, and by two people. Where that matters, let the database refuse the second one.
5. Call `rerun()` after the work when the page above the button shows the data.

Next: [Inside your application](https://script-ui.runio.dev/tutorials/your-application.md).
