Search code examples
phpcakephpcakephp-3.0user-input

Cakephp 3 input auto label


I have a code in my indext.ctp:

<?php echo $this->Form->input('full_name'); ?>

It gives me enter image description here

Label is named Full Name my target is Full name

I know i can use:

<?php echo $this->Form->input('full_name', ['label'=>'Full name']); ?>

My question is: Can i do it globaly? Somehow override ucwords(); using in auto generating labels to ucfirst(); ?


Solution

  • Cakephp generate the label text (when not provided) here

    It uses Inflector::Humanize() (see the manual)

    I guess you can override the default helper (remember that input() is deprecated and you should use control() instead)

    class MyFormHelper extends FormHelper
    {
    
        public function control($fieldName, array $options = [])
        {
            if(!isset($options['label']))
                $options['label'] = // you own code here;
            return parent::control($fieldName, $options);
        }
    }
    

    then in your AppView.php initialize() you load your helper

    $this->loadHelper('Form', [
        'className' => 'MyForm',
    ]);
    

    So when you want to define a custom label you use the 'label' option

    <?php echo $this->Form->input('full_name', ['label'=>'Insert the full name here']); ?>
    

    Instead if you don't set the 'label' option

    <?php echo $this->Form->input('full_name'); ?>
    

    the helper will use your logic

    I tested the behavior and it works in my forms