[英]In Zf2, how to add a error css class on validation failed
當ZF2驗證失敗時,我想在輸入文本框周圍添加紅色邊框。 我在考慮ZF2是否提供在驗證失敗的情況下添加/設置CSS類的方法。 如果可能僅使用Zend Validation / Form API,則更好。 我不考慮客戶端(javascript / jQuery)解決方案。
更新:
我正在使用這樣的表單行元素
<div class="row">
<div><?php echo $this->formLabel($form->get('first_name')); ?></div>
<div><?php echo $this->formElement($form->get('first_name')); ?></div>
<div><?php echo $this->formElementErrors($form->get('first_name'), array('class' => "field-validation-error")); ?></div>
</div>
您可以使用FormRow視圖助手 ,它將使用CSS類(默認為“ input-error”)呈現無效元素。
在模板中,用法非常簡單:
echo $this->formRow($element);
或者如果您要自定義類:
echo $this->formRow()->setInputErrorClass('my-error-class')->render($element);
如果要向輸入中添加特定的“錯誤”類,則需要修改相關的Zend\\Form\\View\\Helper\\Form*
類,因為它們是對Zend\\Form\\ElementInterface
對象的自省,並呈現所需的HTML。
例如:
// \MyModule\Form\View\Helper\MyCustomFormElement.php
class MyCustomFormElement extends \Zend\Form\View\Helper\FormElement
{
public function render(Element $element)
{
$errors = $element->getMessages();
if (! empty($errors)) {
$classes = $element->getAttribute('class');
if (null === $classes) $classes = array();
if (! is_array($classes)) $classes = explode(' ', $classes);
$classes = array_unique(array_merge($classes, array('my-error-class')));
$element->setAttribute('class', implode(' ', $classes));
}
return parent::render($element);
}
}
然后只需通過注冊具有相同名稱的可調用項來替換默認的表單元素助手。
// Module.php
public function getViewHelperConfig()
{
return array(
'invokables' => array(
'form_element' => 'MyModule\Form\View\Helper\MyCustomFormElement',
),
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.