1

Currently on Drupal 8 beta 7.

I'm trying to build a form with separate "submit" and "cancel" buttons. The cancel button has some separate cleanup work to do. I've tried to follow the documentation and examples to create a custom form handler to manage this. Here's my actions block from my form.

    $form['actions']['#type'] = 'actions';
    $form['actions']['cancel'] = array(
      '#type' => 'submit',
      '#value' => 'Cancel',
      '#button_type' => 'cancel',
      '#submit' => array('uso_cancelForm'),
    );
    $form['actions']['submit'] = array(
      '#type' => 'submit',
      '#value' => 'Submit',
      '#button_type' => 'primary',
    );

Then, in my form object, I define the custom handler.

public function uso_cancelForm(array &$form, FormStateInterface $form_state) {
    drupal_set_message("Editing cancelled");
    // Handle state information here
}

However, pressing the cancel button has no effect, except to log an error:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'uso_cancelForm' not found or invalid function name in Drupal\Core\Form\FormSubmitter->executeSubmitHandlers() (line 116 of /{redacted}/core/lib/Drupal/Core/Form/FormSubmitter.php).

So it looks like, for some reason, Drupal can't find my uso_cancelForm function, which is sitting in the form object definition right next to validateForm and submitForm. The "Submit" button calls submitForm without a hitch.

What am I doing wrong here?

I've figured out that if I move my custom uso_cancelForm function into my .module file, Drupal finds and runs it, but this solution won't work as a long-term solution, because I need to use $this in the code that the cancel function executes.
So, clearly, my form's public functions aren't in scope when the button press is being handled, although the standard validateForm and submitForm functions are. I tried adding include_once "src/Form/{my form filename}.php"; to my .module file, but this doesn't help.

Is there some other way I need to let Drupal know about this method, so that the FormSubmitter will know about it and call it?

0

1 Answer 1

4

Use '::uso_cancelForm' or [$this, 'uso_cancelForm'].

1
  • In my case [$this, 'uso_cancelForm'] worked for me, and the other threw an error. Oct 24, 2018 at 17:53

Your Answer

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

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