I find that in Drupal 8 we can specify the submit/validate callbacks as objects. So I was wondering, if we are form-altering a certain form, how do we specify the submit callback as an object?

Like if we suppose we have a class in a file like:


namespace Drupal\mymodule\Form

class FormHelper {
  public static submitHelper(array &$form, FormStateInterface $form_state) {
    ... Some codes here... 

Now can I reference this function in a hook_form_alter()? If so, how?

This is how it is done right now, like in the Drupal 7 way.

$form['#submit'][] = 'submitHelper';

Of course, this helper function was in the module file itself.

Also I'd like to ask if this is a good practice in Drupal 8 to separate these callbacks, and put them in a separate class file, so that the module file remains clean and lazy loading works properly.

  • I'm not quite 100% on what you're asking, but I think the answer might be: $form['#submit'][] = 'Drupal\mymodule\Form\FormHelper::submitHelper'; – Beebee Jul 11 '18 at 10:21
  • Yes thats what I was asking. Actually I tried this for an element #submit, but it was not really working. Also it is a good practice to separate the callbacks from the module file? – Pratip Ghosh Jul 11 '18 at 11:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.