Base Container API
Working with child elements
In addition to methods defined in HTML_QuickForm2_Node, Container defines DOM-like API for handling of child elements: appendChild(), insertBefore(), removeChild(), getElementById(), getElementsByName(). Those who have worked with Javascript or PHP's DOM extension should find these familiar.
DOM-like API for Container
<?php
$fieldset = new HTML_QuickForm2_Container_Fieldset();
$radioOne = $fieldset->appendChild(
new HTML_QuickForm2_Element_InputRadio('aRadio', array('id' => 'radioOne'))
);
$radioThree = $fieldset->appendChild(
new HTML_QuickForm2_Element_InputRadio('aRadio', array('id' => 'radioThree'))
);
$radioTwo = $fieldset->insertBefore(
new HTML_QuickForm2_Element_InputRadio('aRadio', array('id' => 'radioTwo')),
$radioThree
);
echo $fieldset->getElementById('radioOne') . "\n\n";
$fieldset->removeChild($radioOne);
foreach ($fieldset->getElementsByName('aRadio') as $radio) {
echo $radio . "\n";
}
?>
will output
<input type="radio" value="on" id="radioOne" name="aRadio" />
<input type="radio" value="on" id="radioTwo" name="aRadio" />
<input type="radio" value="on" id="radioThree" name="aRadio" />
A few convenience methods are also available: getElements() returns an
array with all the Container's elements and addElement() creates an
element of a given type and adds it to the Container. Thanks to method overloading you can also
perform addEltype() calls where 'eltype'
is an element type
known to HTML_QuickForm2_Factory
(the next section contains the
list of such types and relevant examples).
SPL interfaces
Container also implements Countable and IteratorAggregate SPL interfaces, allowing to easily count the immediate children and iterate over them. It also has getRecursiveIterator() method which returns an instance of HTML_QuickForm2_ContainerIterator for recursive iteration over all child elements.
SPL interfaces support
<?php
$outer = new HTML_QuickForm2_Container_Fieldset();
$inner = $outer->addElement('fieldset')->setId('inner');
$inner->addElement('text', 'textName')->setId('textId');
echo count($outer) . "\n";
foreach ($outer as $child) {
echo $child->getId() . "\n";
}
echo "\n";
foreach ($outer->getRecursiveIterator() as $child) {
echo $child->getId() . "\n";
}
?>
The above code will output
1
inner
inner
textId