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.

1
2
3
4
5
6
7
8
9
<?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.

1
2
3
4
5
6
<?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.

1
2
3
<?php

$elements = $form->getElements();

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

1
2
3
4
5
<?php

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

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

1
2
3
<?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.

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