1

I need to alter a Redhen Contact form when it is attached to the user registration form. More generically, I need to alter a sub form. The form is added to user_register_form() via hook_form_FORM_ID_alter() in rendhen_contact.module:1029. (I don't think this is specific to Redhen's implementation; I'm just providing this as a reference point.)

The first issue I encountered was that the hook implementation in redhen_contact.module hadn't occurred when my hook was called. In a custom module, I used hook_module_implements_alter() to resolve that (see screenshot at bottom for kpr()). With that I'm still unable to alter, for example, the #title attribute of field_agency_interest. Even if I do $form['redhen_contact]['form']['field_agency_interest']['und']['#title'] or ...['und'][0]['title'] it doesn't change.

I tried using $form['#after_build'][] = 'module_callback_name' but I can't edit the sub form elements.

screenshot of kpr()

How can I alter a sub form added to a form?

0

You probably forgot to reference the $form variable ("&$form").
The alternative to #after_build would be #pre_render, which misses $form_state but should generally be preferred for changes that only affect the rendering of a form.

|improve this answer|||||
  • Thanks @ciss. The callbacks for #after_build and #pre_render return the element (or form) so referencing isn't used here. #pre_render doesn't work either though. I am able to change the title for $form['redhen_contact'] (which is a fieldset) but I can't seem to do anything with the fields. – Chris Rockwell Oct 13 '15 at 13:51
  • I was referring to hook_form_alter(). A common mistake is to forget the argument reference, which makes changes to the $form array ineffective, including any added callbacks. – Fabian Iwand Oct 13 '15 at 15:12
0

I came across this: https://drupal.stackexchange.com/a/129617/7595, which identifies that you have to dig a bit deeper into the element; specifically the ['value'] element.

So, for editing a subform this will work:

function hook_form_alter(&$form, &$form_state, $form_id) {
  $form['redhen_contact']['form']['field_agency_interest']['#pre_render'][] = '_field_agency_interest_pre_render';
}
function _field_agency_interest_pre_render($element) {
  $element[$element['#language']][0]['value']['#description'] = '<a href="test">Test</a>';  

  return $element;
}

I'll note again that I'm using #pre_render because the RedHen module hook was being called after this one and this ensures everything has been added to the form prior to making changes.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.