0

In my Controller I'm loading a form with the following code.

$form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomForm');

Depending on different cases I would like to use different processing of the form.

I see 3 possibilities to handle this:

  1. Use different forms and load the correct depending on the case
  2. Include some hidden fields and evaluate these fields in the submit handler of the form
  3. Use different submit handlers

I think the third possibility is the best one. But when I try to use a custom submit hanlders.

$form['#submit'] = 'custom_module_form_submit';
// or
$form['actions']['submit']['#submit'][] = 'custom_module_form_submit';

They both don't work. How can this be achieved? Is there a better way of doing this?

8
  • Is there a better way of doing this? Yes, use a form builder directly.
    – apaderno
    Apr 30, 2017 at 12:53
  • What do you mean? How?
    – thomas826
    Apr 30, 2017 at 13:29
  • You should already have a form builder, if you are using $form = \Drupal::formBuilder()->getForm('Drupal\custom_module\Form\CustomForm');. Otherwise, that could would give an error. Drupal\custom_module\Form\C‌​ustomForm is supposed to be a form builder class.
    – apaderno
    Apr 30, 2017 at 13:32
  • yes its a custom class extending FormBase. But I still don't get how to change the submit handler. In my controller I am successfully loading and also rendering the form. Now I would like to perform different action depending on some cases and therefor use different submit handlers depending on how the form should be processed.
    – thomas826
    Apr 30, 2017 at 14:07
  • Does the action depend on the clicked button? For example, do you have a Delete, Create new copy, and Save button?
    – apaderno
    Apr 30, 2017 at 15:10

1 Answer 1

1

@kiamlaluno is right, you have to use the form builder directly. But for this question in the comments there is a solution:

... its a custom class extending FormBase. But I still don't get how to change the submit handler. In my controller ...

you can put additional parameters in formBuilder()->getForm('Drupal\custom_module\Form\CustomForm', $param), which you then can use in the form class to build the form differently, for example add different submit handlers:

  public function buildForm(array $form, FormStateInterface $form_state, $param = NULL) {

    if ($param == 1) {
      $form['actions']['submit']['#submit'][] = 'custom_module_form_submit';
    }

  }

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.