summaryrefslogtreecommitdiffstats
path: root/includes/view-helpers/select-field-helper.php
blob: 6aabb65e577b264165cdea947f2b53cceb489982 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
/**
 * Select field implementation.
 *
 * @package giglogadmin
 *
 * SPDX-FileCopyrightText: 2021 Andrea Chirulescu <andrea.chirulescu@gmail.com>
 * SPDX-FileCopyrightText: 2021 Harald Eilertsen <haraldei@anduin.net>
 *
 * SPDX-License-Identifier: AGPL-3.0-or-later
 */

namespace EternalTerror\ViewHelpers;

/**
 * Return HTML code for a selction box with the given options and preselected value.
 *
 * @param string    $name     The name attribute for the selection box.
 * @param array     $opts     The options as arrays of [value, label] pairs. An array
 *                            of single values are also acceptable.
 * @param mixed|int $selected The value of the preselected option, or null if no
 *                            option is preselected.
 * @param string    $blank    Text to use for "no selection", defaults to "Please
 *                            select...".
 * @return string
 */
function select_field(
    string $name,
    array $opts = array(),
    $selected = null,
    string $blank = 'Please select...' ) : string {
    $body = "<option value=\"\">{$blank}</option>";
    foreach ( $opts as $opt ) {
        if ( is_array( $opt ) ) {
            $value = $opt[0];
            $desc = $opt[1] ?? $opt[0];
        } else {
            $value = $opt;
            $desc = $opt;
        }

        $sel = selected( $selected, $value, false );
        $body .= "<option value=\"{$value}\"{$sel}>{$desc}</option>";
    }
    return "<select name=\"{$name}\">{$body}</select>";
}