1

Using Drupal 8.5.3. Currently working within a custom controller to load and alter a form for menu links. To load the form I am using the following:

// Load the menu link field.
  $menu_link_content = MenuLinkContent::create([
    'title' => 'Example link',
    'link' => ['uri' => 'internal:/node'],
    'menu_name' => 'main',
  ]);

  $form = \Drupal::service('entity.form_builder')->getForm($menu_link_content, 'default', $form_state_params);

Simple enough right? From there I go onwards to alter $form inside the same method in the controller. I can change the $form values from there to adjust which menu items are available.

The problem is that I can't seem to add a submit handler.

I've tried both of these to add a submit handler, to no avail.

$form['#submit'][] = 'group_content_submenu_group_link_add_submit';
$form['actions']['submit']['#submit'][] = 'group_content_submenu_group_link_add_submit';

Any ideas on what I could be missing? I'm open to other approaches as well, but I specifically need to be able to set the parent item that this form should be using to present available parent menu link choices.

1
  • You need to modify $form in a form alter hook. The form is already processed when returned by the form builder, then it's too late to add submit handlers.
    – 4uk4
    Commented May 30, 2018 at 8:24

1 Answer 1

1

As per a comment from another user, the form is already processed after being returned by the form builder. That said, you can still alter values, but not add form elements or alter actions.

The solution for me was to do a form alter on the form before hand, and give it a submission handler, along with a hidden field. Then when I get the form in the code above, I now set the hidden field to contain a relevant value (Group ID). In my submission handler, I only proceed if that hidden value != NULL. This prevents me from doing anything on the core entity form which I do not want to affect.

Thanks for the hint 4k4!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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