cakephp 3 add default class to inputs

强颜欢笑 提交于 2019-12-13 03:14:27

问题


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?


回答1:


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',
            ]
        );
    }
}


来源:https://stackoverflow.com/questions/46505025/cakephp-3-add-default-class-to-inputs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!