Form Builder
The form builder is used to save time in building form elements from a
database table. The builder uses Aura.SqlSchema
to reverse engineer a database
table, and generate basic form elements based on the column definitions. It does
NOT make any real assumptions about what type of element it should create beyond
text and textarea elements. For example, it will not make the assumption that you
want a checkbox if you have a CHAR(1) column. It will simply create an input of
type text with a maxlength of 1. However, it is trivial to convert that text
input to a checkbox.
Getting Started
All you need to get started is an instance of PDO
. How you get that PDO
object
is up to you. For example, you might have an instance in a dependency injection
container, or your ORM package may make it easy to get a PDO
object.
<?php
use \Vespula\Form\Builder\Builder;
$pdo = new \PDO('mysql:host=localhost;dbname=test', 'username', '********');
$builder = new Builder($pdo);
Now, take your Vespula.Form
object and set the builder using the setBuilder()
method.
Then, create the elements by calling the build()
method on the form. Optionally, pass initial data.
<?php
use Vespula\Form\Form;
$form = new Form();
$form->id('myForm')->action('/some/action');
$tableName = 'posts';
$form->setBuilder($builder);
// Create the elements base on the table named `posts`;
$form->build($tableName);
// Get an element
echo $form->getElement('title');
Passing Data to the Form
You will likely want to pre-populate the form object with initial data, perhaps from a
database record object. You can pass a third parameter to the build()
method that is
either an array keyed on column names, or an object that extends ArrayAccess
with keys
matching the column names.
For example:
<?php
// $posts can either be an array, or an object that extends ``ArrayAccess``
$post = [
'id'=>1
'title'=>'My post title',
'body'=>'Lorem ipsum dolor sit amet...'
'author_id'=>'juser'
];
$form->build('posts', $post);
Getting the Builder
At any time, you can get the builder from the form to modify as needed.
<?php
$builder = $form->getBuilder();
$builder->setColumnOptions([...]);
$form->build('tablename');
Getting Elements from the Form
Now that you have a form, you can get the elements back using the getElement()
method, passing a column name as the key.
<?php
$form->build('posts', $post);
echo $form->getElement('title');
// <input type="text" id="title" name="title" value="My post title" maxlength="255" />
Remember, you can modify the form element by chaining form methods onto the returned element.
<?php
echo $form->getElement('title')->css('my-css');
// <input type="text" id="title" name="title" value="My post title" maxlength="255" class="my-css" />
Further customization of the form elements is discussed in the next chapter.