This website recently got a major rebuild; if you're missing something, let Lorna know.

Change Form Input Type in CakePHP3



I've been having my first experiences with generated code, generating a new admin backend using CakePHP3 (yes CakePHP is still around, it's alive and doing rather well in fact!). So far it's going great and producing a much more complete solution than I'd have managed for myself on this timescale.

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:

Screenshot from 2016-03-13 13-17-57

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:

Screenshot from 2016-03-13 13-18-32

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!


In: php
Tags: #cakephp