0

I want to alter the form submission handler submit for the search block with a custom module.
Setting $form['#attributes']['class'] works, but the submission handler doesn't seem to be triggered with any of the methods that I have alternatively found in many core and third-party modules.

/**
 * @file
 * Redirect search from search block to XXX.
 */

use Drupal\Core\Form\FormStateInterface;
 
/**
* Implements hook_form_FORM_ID_alter().
*/
function search_redirect_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
    $form['#attributes']['class'][] = 'test-class'; //Working
    $form['#submit'][] = 'search_redirect_search_block_form_submit';
    $form['actions']['submit']['#submit'][] = '_second_submit';
}

function search_redirect_search_block_form_submit(&$form, FormStateInterface $form_state) {
  \Drupal::logger('search_redirect')->notice("the function is triggered"); // Not happening
  \Drupal::service('messenger')->addStatus("the function is triggered"); // Not happening
}

function _second_submit(&$form, FormStateInterface $form_state) {
  \Drupal::logger('search_redirect')->notice("second_submit"); // Not happening
  \Drupal::service('messenger')->addStatus("second_submit"); // Not happening
}
1

Stupid question but have you cleared cache to register the new hook?

Also, try inspecting the form in hook_form_alter to make sure you are attaching the handler to the correct action.

Lastly, I've found that I usually need to reorder the array to include my handler first in order for my actions to actually trigger on form submissions using Drupal core forms that have existing handlers.

As an example, I did like:

$form['actions']['submit']['#submit'] = array_reverse($form['actions']['submit']['#submit']);

which will reverse the array. I also sometimes use array_unshift to pop my handler at the start of the array if the other handlers need to retain their order.

1
  • Thanks for the answer, no luck so far. I have spend some time on hook_form_alter indeed, and drush cr after each change of course.
    – Tritof
    Mar 22 at 9:21

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.