Tip: Build Forms Quicker in CakePHP

I first saw use of the $form->inputs() function for building a form on Johnathan Snook’s blog post about creating a contact form.  After investigating further into the function, I found that it can be used to save quite a bit of time.
Automagic Forms!
Using $form->input() is great, but when you have many fields or you are just creating a quick form there is a better way!  The key is to set up your database table structure properly.  If you follow the naming conventions creating a form is as easy as using the following code in the view (this is for a Contact model… obviously):
<?php
echo $form->create('Contact');
echo $form->inputs();
echo $form->end("Save Contact");
?>
This is pretty nice, but what happens if you have fields that you don’t want the user to fill out?  Use the blacklist!  The following code removes the fieldset and legend along with the fields id, created, and modified.
<?php
$inputs = array('fieldset' => false, 'legend' => false);
$blacklist = array('id', 'created', 'modified');
echo $form->create('Contact');
echo $form->inputs($inputs, $blacklist);
echo $form->end("Save Contact");
?>
Not too bad.  Fully functional form in 5 lines of code!  But wait… There’s more!  You may still want to customize the form a little more to add certain options to some fields.  This can be done with the $inputs array.  Basically all you have to do is add a key in the $inputs array with the field name, and then assign the optional attributes as you would if you were using the $form->input() function.  Here is an example of what the array would look like to add a hint after the “first name” field.
$inputs = array(
'fieldset' => false,
'legend' => false,
'first_name' => array('after' => 'i.e. Lane')
);
The only drawback with assigning the optional attributes is that now the $inputs array must contain a key for every input you want to have a form field for.  I’m sure that there is a better way to do this, but you could do something like this in the controller:
<?php
function add()
{
$schema = $this->Contact->schema();
foreach($schema as &$field)
$field = array();
unset($field);
$this->set(compact('schema'));
}
?>
and then in the view do this:
$inputs = array('fieldset' => false, 'legend' => false);
$inputs = array_merge($inputs, $schema);
$inputs['first_name'] = array('after' => 'i.e. Lane');
This method would get the job done, but would really only be practical if you had a whole bunch of fields. Otherwise creating each $form->input() might be the way to go if you have to assign some options.  Nonetheless,  I’ve found that you can bypass having to set the $options array for specific fields by following the naming conventions, and when that is the case there is nothing better than $form->inputs()!
Related Links