到目前为止,我刚刚发现我可以编写自己的视图助手,但由于我是框架的新手,我不知道该怎么做。我希望有一种更简单的方法!?
答案 0 :(得分:2)
我正准备用我自己的解决方案自己提出这个问题,为社区提供服务,可以这么说,当我看到你在建议中提出问题时。
如果我自己这样说,我的简单而优雅的解决方案使用简单的自定义装饰器。它对收到的内容没有任何作用,但它会改变元素。
class App_Form_Decorator_ErrorClass
extends Zend_Form_Decorator_Abstract
{
protected $_placement = null;
protected $_options = array(
'class' => 'error'
);
public function render( $content )
{
$element = $this->getElement();
if( $element->hasErrors() )
{
$errorClass = $this->getOption( 'class' );
$currentClass = $element->getAttrib( 'class' );
$element->setAttrib( 'class', ( !empty( $currentClass ) ? $currentClass . ' ' . $errorClass : $errorClass ) );
}
return $content;
}
}
用法:
您需要做的就是在 ViewHelper装饰器和您的集合之前添加装饰器。
public function init()
{
$elementDecorators = array(
'ErrorClass',
'ViewHelper',
// etc..
);
// or:
$elementDecorators = array(
array(
'ErrorClass',
array( 'class' => 'custom-class' ) // defaults to 'error'
),
'ViewHelper',
// etc..
);
// then just add the decorators to an element the way you usually do, for instance like so:
$someElement = new Zend_Form_Element_Text( 'someElement' );
$someElement->setDecorators( $elementDecorators );
// etc...
O,PS。:确保在表单中添加正确的前缀路径:
$this->addPrefixPath( 'App_Form', 'App/Form' ); // or your own namespace
答案 1 :(得分:1)
是使用Dojo javascript库 (虽然设置起来可能有点困难) 试试这个让你入门 http://techchorus.net/add-cool-zend-dojo-date-picker-form-element-without-writing-single-line-javascript
它的外观如下:
答案 2 :(得分:0)
我发现这样做的最简单方法是扩展正在使用的相应Form类的isValid()方法,最好设置为库中的My_Standard_Form类。
public function isValid($data)
{
$valid = parent::isValid($data);
foreach ($this->getElements() as $element) {
if ($element->hasErrors()) {
$oldClass = $element->getAttrib('class');
if (!empty($oldClass)) {
$element->setAttrib('class', $oldClass . ' error');
} else {
$element->setAttrib('class', 'error');
}
}
}
return $valid;
}
解决方案的积分转到网站因素博客(http://www.websitefactors.co.uk/zend-framework/2011/06/error-class-on-form-field-errors-using-zend-form/)。