Ik heb net een klein OOP classje gemaakt die een form op het beeld tevoorschijn geeft.
Ik ben totaal niet tevreden met het renderen van forms.
Ik heb tot nu toe 1 element gemaakt en dat is de 'text' element.
Hebben jullie wat tips om het renderen beter laten te verlopen?
<?php
class Form
{
private $_fields = array();
private $_attribs = array();
//todo
public function setAttrib($attribName, $attribValue) { $this->_attribs[$attribName] = $attribValue; }
public function getAttrib($attribName) { return $this->_attribs[$attribName]; }
public function addField($field)
{
$this->_fields[] = $field;
}
public function render()
{
$returnValue = '<form';
if (isset($this->_attribs['method']))
{
$returnValue .= ' method="' . $this->_attribs['method'] . '"';
}
else
{
$returnValue .= ' method="post"';
}
if (isset($this->_attribs['action']))
{
$returnValue .= ' action="' . $this->_attribs['action'] . '"';
}
$returnValue .= '>';
foreach ($this->_fields as $field)
{
$returnValue .= $field->render();
}
$returnValue .= '</form>';
return $returnValue;
}
}
?>
Form_Element:
<?php
class Form_Element
{
public $_properties = array();
public $_label = '';
public $_name = '';
public $_value = '';
public function __construct($fieldName)
{
$this->_name = $fieldName;
}
public function setProperty($property, $value)
{
$this->_properties[$property] = $value;
}
public function setValue($value)
{
$this->_value = $value;
}
public function setLabel($label)
{
$this->_label = $label;
}
}
?>
Form_Element_TextField:
<?php
class Form_Element_TextField extends Form_Element
{
public function render()
{
$returnValue = '';
if (isset($this->_label))
{
$returnValue .= '<label>' . $this->_label . '</label>';
}
$returnValue .= '<input type="text"';
$returnValue .= ' name="' . $this->_name . '"';
foreach ($this->_properties as $prop => $value)
{
$returnValue .= ' ' . $prop . '="' . $value . '"';
}
$returnValue .= ' />';
return $returnValue;
}
}
?>