left It’s quite common to place a checkbox’s label at it’s right side, because it just seems natural. But if a form has all the inputs arranged in a label-first fashion, it might look nicer when the labels of a checkbox will be on the left side as well.

Although CakePHP provides a lot of ways to customize pretty everything, I couldn’t find anything in the docs on how to place the label of a checkbox on it’s left side.

When inserting a new input, there is an option called ‘format’. For as far as I can see, there isn’t much documentation on this option, but it basically controls the order of the elements of an input.

For example, the default format for a text input looks like this:

$options['format'] = array(
    'before', 'label', 'between', 'input', 'after', 'error'
);

The 'label’, 'input’ and 'error’ elements are the ones we are looking for. In the FormHelper, the elements have a different order:

// lib/View/Helper/FormHelper.php

case 'checkbox':  
    $input = $this->checkbox($fieldName, $options);
    $format = $format ? $format : array(
        'before', 'input', 'between', 'label', 'after', 'error'
    );

To get the label on the left side, all we need to do is provide our own format:

echo $this->Form->input('is_private', array(  
    'type' => 'checkbox',
    'format' => array(
        'before', 'label', 'between', 'input', 'after', 'error'
    )
));

Alternatively, we can add this to a custom FormHelper, so it will be applied to all input elements:

// app/View/Helper/CustomFormHelper.php

App::import('Helper', 'Form');

class CustomFormHelper extends FormHelper {

    public function input($name, $options = null) {
        if (!$options) $options = array();

        // Set the default format for all inputs, so a
        // checkbox will get a label in front of it
        $options['format'] = array(
            'before', 'label', 'between', 'input', 'after', 'error');

            return parent::input($name, $options);
        }
}

Name this 'CustomFormHelper.php’ and save it in 'View/Helper’.

With CakePHP 2.0, we can use helper aliasing to use this custom helper as our default form helper:

// app/Controller/AppController.php

public $helpers = array(  
    'Form' => array(
        'className' => 'CustomForm'
    )
);

This way, we can still use the Form helper in views, with the label of each input being on the left side.

You might have been wondering what the 'before’, 'between’ and 'after’ elements are doing in there. Well, they can be used to add extra elements to the input, such as span tags around the input:

echo $this->Form->input('is_private', array(  
    'type' => 'checkbox',
    'between' => '<span>',
    'after' => '</span>'
));

So that’s how the position of the label can be customized.