Is it possible to use hook_form_alter() on a hook_form_alter() function already defined in another module?

For example, if I want to alter the output of the following hook from the menu module, can I define a function which allows me to alter the renderable array?

function menu_form_node_type_form_alter(&$form, $form_state) { ... }

I have looked at the documentation but can't seem to find anything that suggests this is allowed/possible.

up vote 7 down vote accepted

If you create your own hook_form_alter function in a custom module, you can modify the same form.

All of the $form variables that are passed into all of the form alter hooks are the same. You will need to specify the form you want to modify by checking for $form_id. $form_id happens to be the third argument passed in!

For example:

function MODULE_form_alter(&$form, $form_state, $form_id)
{
    if ($form_id == "YOUR_FORM_ID)
    {
        //modify form here.
    }
}

There is also the order of execution for the hooks, that you can modify using hook_module_implements_alter. Using this hook, you can set your module to be executed last.

For example:

function MODULE_module_implements_alter(&$implementations, $hook)
{
    if ($hook == 'form_alter')
    {
         $group = $implementations['my_module'];
         unset($implementations['my_module']);
         $implementations['my_module'] = $group;
    }
}

That should do exactly what you need to do.

  • Assigning a weight to your module can also solve the execution order problem. – mpdonadio Oct 15 '13 at 14:46

Not as such, but you can just implement your own version of that alter hook to make the changes you need to, and make sure your implementation runs later on.

To do that you'll need to implement hook_module_implements_alter():

function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Push your module's implementations of hook_form_alter(), and derivatives, 
    // to last in the list. This will make it run after menu_form_node_type_form_alter()
    // so you can alter whatever you need to.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}

function MYMODULE_form_node_type_form_alter(&$form, &$form_state, $form_id) {
  // Make changes as usual
}

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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