1<?php
2/**
3 * Example showing how constraints and transformation can be attached to a form.
4 */
5function data_processing()
6{
7    //Step 0: Declare dependencies
8    global $DIC;
9    $ui = $DIC->ui()->factory();
10    $lng = $DIC->language();
11    $trafo = new \ILIAS\Transformation\Factory();
12    $data = new \ILIAS\Data\Factory();
13    $validation = new \ILIAS\Validation\Factory($data, $lng);
14    $renderer = $DIC->ui()->renderer();
15    $request = $DIC->http()->request();
16
17    //Step 1: Define transformations
18    $sum = $trafo->custom(function ($vs) {
19        list($l, $r) = $vs;
20        $s = $l + $r;
21        return "$l + $r = $s";
22    });
23
24    $from_name = $trafo->custom(function ($v) {
25        switch ($v) {
26            case "one": return 1;
27            case "two": return 2;
28            case "three": return 3;
29            case "four": return 4;
30            case "five": return 5;
31            case "six": return 6;
32            case "seven": return 7;
33            case "eight": return 8;
34            case "nine": return 9;
35            case "ten": return 10;
36        }
37        throw new \LogicException("PANIC!");
38    });
39
40    //Step 2: Define custom constraint
41    $valid_number = $validation->custom(function ($v) {
42        return in_array($v, ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"]);
43    }, "This is not a number I know...");
44
45    //Step 3: Define the input field and attach the previously defined constraint an
46    // validation.
47    $number_input = $ui->input()->field()
48        ->text("number", "Put in the name of a number from one to ten.")
49        ->withAdditionalConstraint($valid_number)
50        ->withAdditionalTransformation($from_name);
51
52    //Step 4: Define the form action to target the input processing
53    $DIC->ctrl()->setParameterByClass(
54        'ilsystemstyledocumentationgui',
55        'example_name',
56        'data_processing'
57    );
58    $form_action = $DIC->ctrl()->getFormActionByClass('ilsystemstyledocumentationgui');
59
60    //Step 5: Define the form, plugin the inputs and attach some transformation acting
61    // on the complete input of the form.
62    $form = $ui->input()->container()->form()->standard(
63        $form_action,
64        [ $number_input->withLabel("Left")
65        , $number_input->withLabel("Right")
66        ]
67    )
68        ->withAdditionalTransformation($sum);
69
70    //Step 6: Define some data processing.
71    if ($request->getMethod() == "POST"
72            && $request->getQueryParams()['example_name'] == 'data_processing') {
73        $form = $form->withRequest($request);
74        $result = $form->getData();
75    } else {
76        $result = "No result yet.";
77    }
78
79    //Step 7: Render the form and the result of the data processing
80    return
81        "<pre>" . print_r($result, true) . "</pre><br/>" .
82        $renderer->render($form);
83}
84