gpt4 book ai didi

php - 将类属性添加到表单错误

转载 作者:IT王子 更新时间:2023-10-29 00:08:44 26 4
gpt4 key购买 nike

我正在使用 Zend Framework 2 开发应用程序,我使用 FormRow 帮助程序在表单中呈现标签、输入和错误(如果存在)。

//within the view
echo $this->formRow($form->get('Name'));

当用户提交表单但未填写所需的输入文本字段时,FormRow 会呈现以下错误消息:

<label>
<span>Name: </span>
<input class="input-error" type="text" value="" placeholder="Insert Name Here" name="Name">
</label>
<ul>
<li>Value is required and can't be empty</li>
</ul>

如何为 li 标签设置一个类,以便在之后设置样式?

我知道我可以通过...回显具有所需类属性的 formElementErrors

<?php echo $this->formElementErrors($form->get("Name"), array('class' => "valuerequired", 'message' => "errortestmessage")); ?>

..但是 FormRow 仍然会在没有类的情况下呈现错误消息。

仅供引用,我是这样设置实体的:

public function getInputFilter()
{
if (!$this->inputFilter) {
$inputFilter = new InputFilter();

$factory = new InputFactory();

$inputFilter->add($factory->createInput(array(
'name' => 'Name',
'required' => true,
'filters' => array(
array('name' => 'StripTags'),
array('name' => 'StringTrim'),
),
'validators' => array(
array(
'name' => 'StringLength',
'options' => array(
'encoding' => 'UTF-8',
'min' => 1,
'max' => 100,
),
),
),
)));

$this->inputFilter = $inputFilter;
}
return $this->inputFilter;
}

最佳答案

参见 the code of formElementErrors

基本上你可以这样做:

$this->formElementErrors($elem)
->setMessageOpenFormat('<ul%s><li class="some-class">')
->setMessageSeparatorString('</li><li class="some-class">');

但是这很不方便...

更好的解决方案是通过您自己的类扩展 Zend\Form\View\Helper\FormElementErrors,然后将 View 助手 formElementErrors 注册到您的类。所以基本上你会有这样的东西:

namespace Mymodule\Form\View\Helper;

use Zend\Form\View\Helper\FormElementErrors as OriginalFormElementErrors;

class FormElementErrors extends OriginalFormElementErrors
{
protected $messageCloseString = '</li></ul>';
protected $messageOpenFormat = '<ul%s><li class="some-class">';
protected $messageSeparatorString = '</li><li class="some-class">';
}

最后一件事就是用这个新类注册 View 助手。为此,您在模块 Module.php 中提供以下代码

public function getViewHelperConfig()
{
return array(
'invokables' => array(
'formelementerrors' => 'Mymodule\Form\View\Helper\FormElementErrors'
),
);
}

免责声明:这段代码没有经过测试,如果有错误请告诉我,但我认为这应该会很好。

关于php - 将类属性添加到表单错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13765662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com