Improved form handling in CakePHP 1.3

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

[code language=”php”]
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’);
[/cc]

Which outputs the following HTML:

[code language=”html”]




[/cc]

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…

[code language=”php”]
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’);
[/cc]

Which produces:

[code language=”php”]


New Article

— goes before the label —


— goes after the input —

— goes before the label —


— goes after the input —


[/cc]

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.

%d bloggers like this: