Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is best way to add required mark with label decorator - Zend

i have a question about using Zend_Form_Decorator_Label,in order to get following result when form element is required i need to get Label-text * and i'm wondering how to achive that in most reusable way?

Is it to write new decorator or to override zend_View_helper_FormLabel ? Maybe there are other ways to achive that?

Any help will be appreciate.

like image 394
Axxxon Avatar asked Jan 22 '26 05:01

Axxxon


2 Answers

You can add one of the following options when you create decorator:

  • optionalPrefix: a prefix to the label to use when the element is optional
  • optionalSuffix: a suffix to the label to use when the element is optional
  • requiredPrefix: a prefix to the label to use when the element is required
  • requiredSuffix: a suffix to the label to use when the element is required

Code example:

$elementDecorators = array(
    'ViewHelper',
    array('Label', array('requiredSuffix' => ' *')),
);

$userName = new Zend_Form_Element_Text('userName');
$userName->setDecorators($elementDecorators);
$userName->setLabel('User Name');

Or alternatively you can explicitly set suffix/prefix on existing decorator:

$userName->getDecorator('Label')->setReqSuffix(' *');
$userName->getDecorator('Label')->setOptSuffix('(Optional) ');
like image 141
ainokna Avatar answered Jan 25 '26 22:01

ainokna


Since the Label decorator adds the CSS class required to the <label> element attached to a form input element specified as required, I have been able to add a symbol (like an asterisk) by using the CSS :after selector with a content() declaration:

label.required:after {
    content: "*";
}

But, I find it can be tricky to get the spacing right, to get the asterisk to render in bold or in the color I want, etc. As a result, I often just fall back to using CSS to render the label itself in bold or in a different color, and then add a legend ("Bold/Red fields are required" or some such) at the top or bottom of the form (often by creating my own custom legend decorator, but sometimes in the view-script itself).

like image 39
David Weinraub Avatar answered Jan 26 '26 00:01

David Weinraub



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!