Adding * To Required Zend_Form Field Using CSS

AttachmentSize
required-field.png306 bytes

You want to add an asterisk to required fields, huh?

add asterisk to zend form required element

There are many approaches to accomplish this. One among them is setting the requiredSuffix option to the label decorator of the form element. Assuming $element is your Zend_Form_Element object:

<?php
$element
->getDecorator('label')->setOption('requiredSuffix'' * ');
?>

Another option is to add the * while setting the label.

<?php
$element
->setLabel('My Label *')
?>

The third, which I am currently using in one of my Zend Framework powered applications is adding * using CSS. The default label decorator generates the following mark-up.

<label class="required" for="username">Email address</label>

It sets the label class to "required". We add a four line CSS to add * next to the text that appears within the label tag. You just need an image. I have attached a sample image to this post. Feel free to use it.

Here goes the CSS

.required
{
background-image:url(/path/to/your/images/dir/required-field.png);
background-position:top right;
background-repeat:no-repeat;
padding-right:10px;
}
Content Type: 
FOSS Project: 
Technology: 

Comments

Smart solution with CSS, thx

You're welcome.

You could also go this way:

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

and then place the star where you want it to be.

Just to let everyone know:

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

This doesn't work in IE, so using the PNG image as asterisk is a good choice if you care about those poor people with IE.

So can I add an asterisk to required fields of the email php form that i use? How to paste this code there?

Thanks for the tip

Here is another way of soing this:

$element->getDecorator('label')->setRequiredSuffix(' * ');

great sitte!

First solution simply doesn't work!

The first possibility is the only one who's accessible. Screen reader can see the *, with CSS they can't !

Add new comment