Change Form Input Type in CakePHP3
One thing is bothering me though: it guesses form input types from the database column types, which mostly works well but sometimes it picks something that doesn’t reflect the way that the user will store information in this field. It’s actually pretty easy to change the forms that get generated though, so here’s an example.
I have a field in my database called “enabled” which is declared as int(1)
– it holds a boolean value.
The view code simply says which form field to output:
echo $this->Form->input('enabled');
For most fields this is all I need, but this one gives me a number field like this:
In this case, I would prefer a tick box for the user to just indicate yes/no on the value. I can tell CakePHP that by passing an additional argument to the input()
method containing the options I want to use, and setting the type
option like this:
echo $this->Form->input('enabled', ['type' => 'checkbox']);
This gives the result I wanted:
You can change all kinds of things really easily – try adding a label
option (I’m sure I’m not the only person with not-useful-to-humans column names in an old database!) to add better labels. There is also really excellent documentation in the Cake Cookbook – see this page for details of creating and modifying form fields.
One thing I was worried about with generated code was maintenance – what if I generated a form, customised it, and had to regenerate because we added a field? In fact since we use git this works brilliantly, I just generate the new version of a file and then pick out the bits I want and throw away all the other changes!
Haven’t used CakePHP for a while (Since the 2 branch) but if you set your field in the database as a tinyint(1) cake will automatically use a checkbox for the field.
If you declare your field as `TINYINT(1)` (instead of `INT(1)`) cakephp will automatically treat it as a boolean, and thus the FormHelper will output a checkbox.
I think most code generators guess the input correctly when using tinyint(1) as a type. Doesn’t CakePHP support that?
It doesnt on purpose to avoid ambiguity, tinyint(1) has always been the Cake Convention :)
The “type” attribute of FormHelper is valid for CakePHP 2.x as well.
Pingback: March 2016 Newsletter - Nomad PHP