3

Is it possible to use a variable inside the error message referring to the label of the form element? It's possible to map custom variables like %hostname% (in email validator) and the %value% is also available, but I'd like to have the form label as well.

I could't find it in the ZF codebase, but the use case is for example that the Zend_Validate_NotEmpty can return a message like:

"The field %label% is required and can't be empty"

Instead of:

 "Value is required and can't be empty"

2 Answers 2

1

I think it's not possible without subclassing the validators. The Zend_Validate classes are not intended to be used with Zend_Form_Element only. Having a %label% in the message would introduce a coupling between both components.

A possible solution could be to create custom validators by extending Zend_Validate_NotEmpty (or whatever validators you are using) and pass the label to the constructor. This way, you could compose the appropriate message every time you instantiate it.

EDIT:

If you follow the method above, you could even define your own %label% "magic variable" and attach it to a member of the class. See the $_messageVariables member in the Example #2 in the Zend Framework documentation: Writing validators

Hope that helps...

Sign up to request clarification or add additional context in comments.

1 Comment

Hi, in this case we need to inject the label all the time, which is duplicate of work and a possible point of failure which I'm not a fan of. Right now, I think of (mis-)using the decorator for this. The decorator is (as far as I know) aware of the element, including label and can easily perform a ´str_replace()´ over the error message. I'll work this out and post and answer when I have something.
0

I finally went with the decorator. The solution of dinopmi is possible, however you need to inject the label all the times. My error decorator for the form element replaces now the %label% to the real label.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.