Search code examples
cakephpcakephp-3.0cakephp-3.x

cakephp 3 add default class to inputs


i'm trying to add a default class for each input in my cakephp 3 app. Example of what i want:

Input: <echo $this->Form->control('email');

Output: <input class="form-control" class="is-invalid"/>

Desired output: <input class="form-control is-invalid"/>

for this i have edited input template of FormHelper

$this->viewBuilder()->setHelpers([
        'Form' => [
            'templates' => [
                'input' => '<input class="form-control" type="{{type}}" name="{{name}}"{{attrs}}/>'
            ]
        ]
    ]);

the problem is that {{attrs}} possibly contain others classes. Do you have any idea how to do it?


Solution

  • solved :D create a FormHelper to override method control and add class.

    class BootstrapFormHelper extends FormHelper{
        public function control($fieldName, array $options = []){
            if($this->request->is('post') && !$this->isFieldError($fieldName)){
                $options['class'] = 'form-control is-valid';
            }else{
                $options['class'] = 'form-control';
            }
            return parent::control($fieldName, $options);
        }
    }
    

    then change your AppView

    class AppView extends View{
        public function initialize()
        {
            $this->loadHelper(
                'Form', [
                    'className' => 'BootstrapForm',
                ]
            );
        }
    }