February 14, 2017 by Christoff Truter PHP
Up until this point we've got a very basic, but working drop-down list implementation, it is however quite fragile at the moment, since we're not doing enough validation checks not to mention all properties being public.
Lets have a look at the public properties exposed by our HtmlSelectElement.
class HtmlSelectElement extends HtmlFormControlElement implements IHtmlInnerHtml { public $Name; public $Disabled; public $Children; public $Selected;
...
abstract class HtmlFormControlElement extends HtmlElement { protected $Value; public function GetValue() { return $this->Value; } abstract function SetValue($value);
Getting the protected value should be a fairly generic thing, setting it however will likely differ from element to element, so we're making its "setter" abstract.
Our SetSelected method now becomes SetValue.
Getting back to the $Children property, we need to write a setter to allow the developer to add proper value to this property, now some of the code is very similar to the SetValue method, so we're going to reuse some of it.
Observe the updated snippet.
class HtmlSelectElement extends HtmlFormControlElement implements IHtmlInnerHtml { public $Disabled; private $Name; private $Children; public function __construct($name, array $children = [], $value = null, $disabled = false, $context = 'POST') { $this->Name = $name; $this->Disabled = $disabled; $userValue = $this->GetUserValue($context); $this->SetChildren($children, ($userValue === null) ? $value : $userValue); } private function setChild($child, $value) { $optionValue = (string)$child; $child->Selected = ($optionValue == $value); if ($child->Selected) { $this->Value = $optionValue; } } public function SetValue($value) { foreach($this->Children as $child) { $this->setChild($child, $value); } } public function SetChildren(array $children, $value = null) { foreach($children as $child) { if ($child instanceof HtmlOptionElement) { $this->setChild($child, $value); } else { throw new Exception("Type of HtmlOptionElement expected in drop-down list $this->Name"); } } if (count($children) != count(array_unique($children))) { throw new Exception("Non unique values assigned to drop-down list $this->Name"); } $this->Children = $children; }
class HtmlOptionElement extends HtmlElement implements IHtmlInnerText { ... public function __toString() { return (string)(($this->Value === null) ? $this->Text : $this->Value); } }
February 17, 2017
PHP drop-down list - Part 5 (Custom Serialization)February 15, 2017
PHP drop-down list - Part 3 (Maintaining State)February 14, 2017
PHP drop-down list - Part 2 (Serialization of elements to HTML)February 14, 2017
PHP drop-down list - Part 1 (Knowing thy elements)February 14, 2017