psf
combobox.php
1 <?php
2 
3 // Part of php simple framework (psf)
4 
5 // This program is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 
10 // This program is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
14 
15 // Copyright (c) Petr Bena <petr@bena.rocks> 2015 - 2018
16 
17 if (!defined("PSF_ENTRY_POINT"))
18  die("Not a valid psf entry point");
19 
20 require_once (dirname(__FILE__) . "/element.php");
21 
23 {
24  public $Enabled = true;
25  public $Value = NULL;
26  public $Selected = false;
27  public $Text = NULL;
28 
29  public function __construct($_value = NULL, $_text = NULL, $_parent = NULL)
30  {
31  $this->Value = $_value;
32  $this->Text = $_text;
33  }
34 
35  public function ToHtml()
36  {
37  $_e = "<option";
38  if ($this->Selected)
39  $_e .= ' selected="selected"';
40  if ($this->Value !== NULL)
41  $_e .= ' value="' . $this->Value . '"';
42  $_e .= ">";
43  $_e .= $this->Text . "</option>";
44  return $_e;
45  }
46 }
47 
48 class ComboBox extends HtmlElement
49 {
50  public $Multiple = false;
51  public $Enabled = true;
52  public $Name;
53  public $Autofocus = false;
54  public $OnChangeCallback = NULL;
55  public $Items = [];
56 
57  public function __construct($_name = NULL, $_parent = NULL)
58  {
59  $this->Name = $_name;
60  parent::__construct($_parent);
61  }
62 
63  public function AddDefaultValue($value, $text = NULL)
64  {
65  if ($text === NULL)
66  $text = $value;
67  $item = new ComboBoxItem($value, $text, $this);
68  $item->Selected = true;
69  $this->Items[] = $item;
70  }
71 
72  public function AddValue($value, $text = NULL)
73  {
74  if ($text === NULL)
75  $text = $value;
76  $item = new ComboBoxItem($value, $text, $this);
77  $this->Items[] = $item;
78  }
79 
80  public function ToHtml()
81  {
82  $_e = "<select";
83  if ($this->Name !== NULL)
84  $_e .= " name=\"$this->Name\"";
85  if ($this->Style !== NULL)
86  $_e .= " style=\"" . $this->Style->ToCss() . "\"";
87  if ($this->OnChangeCallback !== NULL)
88  $_e .= ' onchange="' . $this->OnChangeCallback . '"';
89  $_e .= ">\n";
90  foreach ($this->Items as $item)
91  $_e .= " " . $item->ToHtml() . "\n";
92  $_e .= "</select>";
93  return $_e;
94  }
95 }