Could probably do with a getter or two, but I've not actually got a genuine use for it (I'm a template slave) so don't know from first hand if these would be valuable.
Comments to be added when I find the effort
Keyword: Simple :p
Code: Select all
<?php
class HTMLForm
{
private $_members = array();
private $_properties;
public function __construct($name, $action, $method = 'post')
{
$this->_properties['name'] = htmlentities($name);
$this->_properties['action'] = htmlentities($action);
$this->_properties['method'] = htmlentities($method);
}
public function addMember(HTMLFormMember $member)
{
$this->_members[] = $member;
}
public function setProperty($property, $value)
{
$this->_properties[htmlentities($property)] = htmlentities($value);
}
public function renderHTML()
{
$output = '<form';
foreach ($this->_properties as $name => $val)
{
$output .= ' ' . $name . '="' . $val . '"';
}
$output .= '>' . chr(10);
foreach ($this->_members as $member)
{
$output .= $member->renderHTML() . chr(10);
}
$output .= '</form>';
return $output;
}
}
class HTMLFormMember
{
private $_properties;
private $_innerHTML;
private $_type;
public function __construct($name, $type)
{
$this->_properties['name'] = htmlentities($name);
$this->_type = htmlentities($type);
}
public function setProperty($property, $value)
{
$this->_properties[htmlentities($property)] = htmlentities($value);
}
public function setInnerHTML($text, $escape = true)
{
if ($escape) $text = htmlentities($text);
$this->_innerHTML = $text;
}
public function renderHTML()
{
$output = '<' . $this->_type;
foreach ($this->_properties as $property => $value)
{
$output .= ' ' . $property . '="' . $value . '"';
}
if (!is_null($this->_innerHTML))
{
$output .= '>' . $this->_innerHTML . '</' . $this->_type . '>';
}
else
{
$output .= '/>';
}
return $output . chr(10);
}
}
$form = new HTMLForm('myForm', '#');
$member = new HTMLFormMember('myTextarea', 'textarea');
$member->setProperty('rows', '2');
$member->setProperty('cols', '30');
$member->setInnerHTML('testing 123... \'"');
$form->addMember($member);
$member2 = new HTMLFormMember('mySubmit', 'input');
$member2->setProperty('type', 'submit');
$member2->setProperty('value', 'click me!');
$form->addMember($member2);
echo $form->renderHTML();
?>Code: Select all
<form name="myForm" action="#" method="post">
<textarea name="myTextarea" rows="2" cols="30">testing 123... '"</textarea>
<input name="mySubmit" type="submit" value="click me!"/>
</form>