Magento 1.9 – Placeholder for Admin Form Field

adminformmagento-1.9

I have an admin form where there is one field like this

$founderFieldset->addField('founder_name', 'text', array(
        'label'     => Mage::helper('vendors')->__('Founder Name'),
        'required'  => true,
        'class'     => 'required-entry',
        'name'      => 'founder_name',
));

Now Magento converts this code to HTML and the result is something like

<input type="text" id="founder_name" name="founder_name" class="required-entry" />

Now how can put a placeholder for this field?
So I want the resulting HTML to come like this

<input type="text" id="founder_name" name="founder_name" class="required-entry" placeholder="Blah blah..." />

Best Answer

You cannot do this out of the box.

Why not

First, some explanations on why it doesn't work.
When adding a text field to a form, this class is instantiated and used Varien_Data_Form_Element_Text.
This class has a method called getHtmlAttributes that looks like this:

public function getHtmlAttributes()
{
    return array('type', 'title', 'class', 'style', 'onclick', 'onchange', 'onkeyup', 'disabled', 'readonly', 'maxlength', 'tabindex');
}

this means that any of the attributes you supply in your config array that are listed in the method will appear on the input field when this is rendered.
As you can see, there is no placeholder attribute.

Solution

You can create your own input renderer that should be a block class in your module.
So you can create this file: app/code/local/[Namespace]/[Module]/Block/Adminhtml/Text.php with this content.

<?php 
class [Namespace]_[Module]_Block_Adminhtml_Text extends Varien_Data_Form_Element_Text
{
   public function getHtmlAttributes()
   {
        $attributes = parent::getHtmlAttributes();
        $attributes[] = 'placeholder';
        return $attributes;
   }   
}

And now you need to tell your form to use this class for text inputs.
You can do that by specifying somewhere above the code you have in your question

$founderFieldset->addType('text', '[Namespace]_[Module]_Block_Adminhtml_Text');  

or better yet

$founderFieldset->addType('text', $fieldset->addType('text', Mage::getConfig()->getBlockClassName('[module]/adminhtml_text')););  

Now you can just specify the placeholder in your config array for the field.

$founderFieldset->addField('founder_name', 'text', array(
    'label'     => Mage::helper('vendors')->__('Founder Name'),
    'required'  => true,
    'class'     => 'required-entry',
    'name'      => 'founder_name',
    'placeholder' => $this->__('Blah blah...')
));
Related Topic