Improved form handling in CakePHP 1.3

Here is a typical, simple form done with cake’s form helpers:

echo $this->Form->create('Article', array('action' => 'test'));

echo $this->Form->input('Article.title');
echo $this->Form->input('Article.body');
echo $this->Form->input('Article.user_id', array('type' => 'hidden'));

echo $this->Form->end('Add Aricle with Tags and Comment');

Which outputs the following HTML:

Title

Body

This is fine and all, but one thing worth noting is that default behavior is wrapping each element in a div, and in some cases this may not be desirable. Either a legacy CSS or a front-end developer preference, might require the form to be structured (wrapped) differently.
Let’s see how we can set some defaults for our form with CakePHP 1.3., while simplifying the code a little at the same time by using the inputs() method…

echo $this->Form->create('Article', array('action' => 'test',
'inputDefaults' => array(
'div' => array('tag' => 'p'),
'before' => '-- goes before the label --',
'after' => '-- goes after the input --')));

echo $this->Form->inputs(array('Article.title',
'Article.body',
'Article.user_id' => array('type' => 'hidden')),
array('legend' => 'Article submit'));

echo $this->Form->end('Add Aricle');

Which produces:

New Article

-- goes before the label --

Title

-- goes after the input --

-- goes before the label --

Body

-- goes after the input --

Of course for a simple form this may not be a very significant improvement, but having the ability to set defaults for the entire form and relying on some automagic for the rest, certainly makes one’s life easier.