简体   繁体   English

Zend Form:向元素添加消息

[英]Zend Form: add message to the element

Usually I used Zend Form's messages in the following way: 通常,我通过以下方式使用Zend Form的消息:

Code in form: 代码形式:

$element = new Zend_Form_Element_Text('form_resource_type');
$validator = new Zend_Validate_NotEmpty();
$validator->setMessages(
     array('isEmpty' => 'Please choose type of resource')
);
$element->addValidator($validator);
$element->setRequired(true);
$this->addElement($element);

Code in view: 查看代码:

<?php foreach($subForm->getElementsAndSubFormsOrdered() as $element):?>
     <?php echo $element?>
     <?php foreach($element->getMessages() as    $errorMsg):?>
         <?php echo $this->escape($errorMsg);?>
    <?php endforeach;?>
<?php endforeach;?>

So, for outputting error messages I used getMessages() function. 因此,为了输出错误消息,我使用了getMessages()函数。 But right now under certain circumstances (in case of special combination of fields' values) I need to mark element as invalid and add custom error message. 但是现在在某些情况下(在字段值的特殊组合的情况下),我需要将元素标记为无效并添加自定义错误消息。 I tried to use addError($message) function, but it adds message to _errorMessages property, while getMessages output _messages Zend_Form_Element property. 我尝试使用addError($ message)函数,但是它将消息添加到_errorMessages属性,而getMessages输出_messages Zend_Form_Element属性。

I didn't find function of adding messages to the _messages property. 我没有找到向_messages属性添加消息的功能。 How can I do this? 我怎样才能做到这一点? Or I should not work with this property directly and change a way of outputting error messages in view? 还是我不应该直接使用此属性并更改在视图中输出错误消息的方式?

UPD: UPD:

I use Zend Framework 1.12 我使用Zend Framework 1.12

Since you are accessing the error messages from the form element. 由于您正在访问来自form元素的错误消息。 Then you can try to set message in the element by using the following statement in the controller: 然后,您可以尝试使用控制器中的以下语句在元素中设置消息:

$form->getElement('elementName')->addErrorMessage('custom Message');

You will then be able to print the message in your way. 然后,您将能够以自己的方式打印消息。

You can use markAsError() for marking an element as invalid Custom Error Messages 您可以使用markAsError()将元素标记为无效的自定义错误消息
I think this will do the trick for you 我认为这将为您解决问题

if($error)
{
    $element->addErrorMessage('Custom Error');
    $element->markAsError();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM