9
votes

I am working on a Zend form application where my form contains text boxes with watermarks.

we can achieve this in HTML by the following code:

<input type="text" placeholder="Search" name="q" />

My question is how to add the placeholder attribute in my input-box using Zend form ?

5

5 Answers

20
votes

It's already been mentioned to use:

$element->setAttrib('placeholder', 'Search');

You can also use it like this when extending Zend_Form

$element = $this->createElement('text', 'q', array(
           'placeholder' => 'Search',
           'label'       => 'Search'
));

Or inside the view using Zend_View_Helper_FormText

echo $this->formText('q',null, array('placeholder' => 'Search'));
3
votes

I think you can call settAttrib() on your element like this when you define elements

    $element->setAttrib ( 'placeholder', 'search' );
3
votes

On Zend_Form_Element objects you can specify attributes:

$element->setAttrib('placeholder', 'Search');
2
votes

Here's an update for ZF2.
You'll have to use this in your Zend\Form\Form :

$this->add(
    [
        'name'    => 'q',
        'type'    => 'Text',
        'options' => [
            'label' => 'Search',
        ],
        'attributes' => [
            'placeholder' => 'Search',
        ],
    ]
);

setAttrib doesn't exists, but setAttribute does :

$element->setAttribute('placeholder', 'Search');

But in FormText view-helper, you can't add options anymore, so you have to do :

$element = $form->get('q');
$saved_placeholder = $element->getAttribute('placeholder'); // works even if not defined
$element->setAttribute('placeholder', 'Search');
echo $this->formText($element);
$element->setAttribute('placeholder', $saved_placeholder);

I know, this is an ugly hack !

0
votes

My solution using jQuery

var elements = ['email', 'password', 'password_confirm'];
$j(elements).each(function(i, elem){
    $j('#' + elem).attr('placeholder', $j('#' + elem + '-label label').text());
    $j('#' + elem + '-label').hide();
    if ($j('#' + elem).hasClass('required-entry')) $j('#' + elem).attr('placeholder', $j('#' + elem).attr('placeholder') + ' *');
});