Hi,
stupid question: how do I add an attribute to the url part of the link element with hook_form_alter? I want to add an onfocus attribute with some javascript.
Usually I would do something like $form['field_mytextfield']['und'][0]['value']['#attributes']['onfocus']
but the link element has several fields and no 'value' array.

I tried $form['field_mylinkfield']['und'][0]['#attributes']['url']['onfocus'] and a few other variants but it does not work. Any idea?

Comments

wouter99999’s picture

ah, I think I found it: I can do it in after_build using
$form['#after_build'][] = 'mytheme_after_build'; in mytheme_form_alter
and then doing the stuff in
function mytheme_after_build($form, &$form_state) {
//things to alter
..
return $form;
}

guschilds’s picture

FWIW, I was having trouble applying the 'placeholder' attribute to a Link field. I was applying them to other fields in hook_form_alter, but this was not possible as link_field_process() in link.module is called after that.

Assigning a function to $form['#after_build'], as shown above, I was able to assign a placeholder value to a Link field:
$form[$field_name][$field_language][0]['url']['#attributes']['placeholder'] = $placeholder;

Swap $field_name, $field_language, and $placeholder appropriately.

Also, swap 'url' for 'title' if you'd like to manipulate the #attributes of the title field.

Thanks for posting your solution, wouter99999

guschilds’s picture

Version: 7.x-1.0-alpha1 » 7.x-1.0
jnavane’s picture

Issue summary: View changes

Sorry. I removed the OFFTOPIC answer.

dqd’s picture

Priority: Normal » Minor
Status: Active » Closed (fixed)

Original issue is fixed. Last comments are OFFTOPIC.

arlingtonvoicellc’s picture

Not reopening, but adding an update to the answer. Using guschild's suggested format would not work for me. This does however:

$form['field_NAME']['und'][0]['url']['#attributes']['placeholder'] = t('Some Text');
return $form;

In case anyone else hits that issue.