【问题标题】:cakephp 3: change class input errorcakephp 3:更改类输入错误
【发布时间】:2015-05-01 06:52:01
【问题描述】:

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

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

解决方案:
$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-&gt;Form-&gt;error('field', null, ['escape' =&gt; false]);,但这是一项艰巨的手动任务。我想保留所有字段错误的默认值。我可以编辑 FormHelper.php 类。但是,我认为这不是一个好主意。

我的表单模板是:

'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}}',

【问题讨论】:

  • 更改哪些字段的类名确切inputtextarea 等实际输入字段?为什么要删除将具有适当的error 类集的错误容器?您是否也删除了其他人,而不仅仅是此处显示的 textareas ?
  • 我可以在所有表​​单字段出错时更改它们的类名。我将 errorClass 选项放在 loadHelper 中: $this->loadHelper('Form', [ 'templates' => 'admin_form_template', 'errorClass' => 'another-class', ]);但是,第 2 期,我还不能。我需要为 cakephp 设置 escape => false 不会转义 html 标签...

标签: forms cakephp cakephp-3.0


【解决方案1】:

到问题的第二部分:您可以像下面的代码一样扩展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 中删除该别名。

【讨论】:

  • 非常好!工作得很好!谢谢!
【解决方案2】:

对于那些想要一个“简单的解决方案”来转义一些字段上的错误消息的人,你不能简单地将转义选项设置为 false:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-30
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多