Drupal - Adding form placeholders to text input fields
That's an HTML5 placeholder, you can just add it as an attribute to any element and HTML5 enabled browsers will react accordingly:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'some_form') {
$form['some_element']['#attributes']['placeholder'] = t('Placeholder text');
}
}
A short recursive function like this might be handy if you want to automatically add placeholders for every textfield in a form (based on the field's title in this example):
function MYMODULE_auto_placeholders(&$element) {
if ( isset($element['#type']) && $element['#type'] == 'textfield') {
// set placeholder
$element['#attributes']['placeholder'] = $element['#title'];
// hide label
$element['#title_display'] = 'invisible';
}
foreach (element_children($element) as $key) {
MYMODULE_auto_placeholders($element[$key]);
}
}
Then in your form alter function just call
MYMODULE_auto_placeholders($form);
That method will work for pretty much every textfield on a form, with the exception of those that are added in #process
functions (like the alt and title textfields of an image field for example).
I tried Clive's answer:
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'some_form') {
$form['some_element']['#attributes']['placeholder'] = t('Placeholder text');
}
}
But to my surprise, I got the placeholder in wrapper of textfield, not textfield itself. Then I tried a variation as follows, it worked!
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'some_form') {
$form['some_element']['und'][0]['value']['#attributes']['placeholder'] = t('Placeholder text');
}
}
Just add the placeholder in the #attributes array for the form field element, such as in the following code.
$form['my_textfield'] = array(
'#type' => 'textfield',
'#attributes' => array(
'placeholder' => t('My placeholder text'),
),
);