Ok, so I ran into a situation where I needed to added an onclick event to a link controlled by link module. There are no settings within the link field to add an onclick event, so I wrote this function to add a field to the link settings for an onclick event. I have it in a hook_form_alter() but you could put it in a better hook. It works for me but if anyone has thoughts on how to improve it, I would appreciate feedback.

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {

  if($form_id == 'field_ui_field_edit_form' && $form['#field']['module'] == 'link') {
    $form['instance']['settings']['attributes']['onclick'] = array(
      '#type' => 'textfield',
      '#title' => t('Onclick event'),
      '#description' => t('When output, this link will have this onclick event'),
      '#default_value' => empty($form['#instance']['settings']['attributes']['onclick']) ? '' : $form['#instance']['settings']['attributes']['onclick'],
      '#weight' => -20,
    );
  }
}

Comments

HongPong’s picture

this never got rolled in, but for the Drupal 6 link module see:
https://drupal.org/node/1126838 #1126838: Add onClick field to Link