Adding Elements to a form

Outputting form elements on-the-fly is straightforward. There may be cases where you want to preload your form object with all the elements and then pass that form object to a view. You can accomplish this by using the addElement() and getElement() methods on the form object.

<?php
$form = new \Vespula\Form\Form();
$text = $form->text()->name('foo')->id('foo')->value('Lorem ipsum');
$textarea = $form->textarea()
                 ->name('comments')
                 ->value('Lorem ipsum')
                 ->placeholder('Enter your comments here');

// Add the element to the form using a key identifier
$form->addElement('foo', $text);
$form->addElement('comments', $textarea);

Getting Elements

Get elements using the getElement() method.

<?php
// Now get the element from the form
echo $form->getElement('foo');
echo $form->getElement('comments');

You can also get all elements from the form.

<?php
$elements = $form->getElements();

You can also get a subset of elements by passing an array of element names.

<?php
$elements = $form->getElements([
    'foo', 'bar'
]);

Once you have an element, you can fluently chain methods to modify it.

<?php
echo $form->getElement('foo')->class('some-css');

Getting Element Attributes

You can get an attribute from an element by calling the getAttribute() method on an element.

<?php
$element = $form->getElement('foo');
$name = $element->getAttribute('name');