cakephp 3: 更改 class 输入错误

cakephp 3: change class input error

我根据文档构建了我的表单模板。似乎一切都很好,直到出现字段错误。现在我有两个问题:

  1. 如何在出现错误时更改 class 表单字段的名称?

解决方案:
$this->loadHelper('Form', [ 'templates' => 'your_template_file', 'errorClass' => 'your-class', ]);

  1. 当字段出错时,如何在 cakephp 的错误消息中设置 escape => false?因为我里面有图标div,比如
<div class="error-message"><i class="fa fa-times"></i> My error</div>

好吧,我得到了部分解决方案。要转义 HTML,我可以在所有字段中输入 $this->Form->error('field', null, ['escape' => false]);,但这是一项艰巨的手动任务。我想使用默认的所有字段错误来逃避。我可以编辑 FormHelper.php class。但是,我认为这不是个好主意。

我的表单模板是:

'formStart'              => '<form {{attrs}} class="form-horizontal" novalidate>',
'inputContainer'         => '{{content}}',
'input'                  => '<input type="{{type}}" name="{{name}}" {{attrs}} class="form-control"/>',
'checkbox'               => '<input type="checkbox" value="{{value}}" name="{{name}}" {{attrs}}/>',
'textareaContainerError' => '{{content}}',
'textarea'               => '<textarea name="{{name}}" {{attrs}} class="form-control"></textarea>',
'select'                 => '<select name="{{name}}" {{attrs}} class="form-control">{{content}}</select>',
'button'                 => '<button {{attrs}} class="btn btn-primary">{{text}}</button>',
'nestingLabel'           => '{{input}}',
'formGroup'              => '{{input}}',

问题的第二部分:您可以像下面的代码一样扩展 FormHelper,这样 escape 将被设置为 false默认

// extended FormHelper, this goes in src/View/Helper
namespace App\View\Helper;
use Cake\View\Helper;

class MyFormHelper extends Helper\FormHelper
{
    public function error($field, $text = null, array $options = []) 
    {
        if (!isset($options['escape'])) {
            $options['escape'] = false;
        }

        return parent::error($field, $text, $options);
    }
}

接下来在 AppController.php

中为这个助手创建别名
public $helpers = [
    'Form' => ['className' => 'MyForm']
];

这还允许您添加更多您自己的定制,您可以随时返回到 FormHelper 的默认实现,只需从 AppController.php.[=16= 中删除该别名即可]

对于那些想要 'easy solution' 转义 某些 字段上的错误消息的人,您不能简单地将转义选项设置为 false :

   <?= $this->Form->input('email', [
                                    "label" => "Email",
                                    "error" => [
                                        "escape" => false
                                    ]
                                ]) ?>