phpinputcakephpdefaultform-helpers

cakePHP Form input label overrides inputDefaults


I'm setting up a user-registration-form in cakePHP, using inputDefaults to match twitter bootstrap requirements for horizontal forms

    echo $this->Form->create('User', array(
            'class' => 'form-horizontal',
            'role' => 'form',
            'inputDefaults' => array(
                'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
                'div' => array('class' => 'form-group'),
                'label' => array('class' => 'col-sm-2 control-label'),
                'between' => '<div class="col-sm-10">',
                'after' => '</div>',
                'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
            )));

Within, I'm using

echo $this->Form->input('username');

to display the form element.

I would like to have custom label, like this:

echo $this->Form->input('username', array('label' => 'Benutzername'));

Unfortunately this overrides my default settings. How can I use default settings and a custom label at once, without redefining all settings for all input elements?


Solution

  • I would do this

    $mainLabelOptions = array('class' => 'col-sm-2 control-label');
    echo $this->Form->create('User', array(
        'class' => 'form-horizontal',
        'role' => 'form',
        'inputDefaults' => array(
            'format' => array('before', 'label', 'between', 'input', 'error', 'after'),
            'div' => array('class' => 'form-group'),
            'label' => $mainLabelOptions,
            'between' => '<div class="col-sm-10">',
            'after' => '</div>',
            'error' => array('attributes' => array('wrap' => 'span', 'class' => 'help-inline')),
            )));
    
    //then I would create a new label options array and have it merged to the main one
    $myLabelOptions = array('text' => 'Benutzername');
    echo $this->Form->input('username', array('label' => array_merge($mainLabelOptions, $myLabelOptions)));
    

    You would be basically "overwriting" but still maintaining the default options.