0

I am trying to handle multiple submit buttons, but the handlers does not get called.

I am following http://www.hooksupport.com/blog/drupal-8-how-handle-multiple-submission-buttons-drupal-8-form, and this is the code I am using.

$form['add_field'] = array
    (
      '#type' => 'submit',
      '#value' => $this->t('Create field'),
      '#submit' => array('::create_field_submit'),
    );

 public function create_field_submit(array &$form, FormStateInterface $form_state){
     drupal_set_message(t('Form Submitted Successfully'), 'status', TRUE);
}

The message I've trying to send does not appear. Why?

  • 1
    Is the first part of your code in the buildForm function ? – guilhom Aug 1 '17 at 7:18
  • No, I want this to work with blockForm.. I thought it should work from there too. – user78028 Aug 1 '17 at 7:30
  • 1
    I've recently been finding that the '::foo' approach doesn't always work. Try using [$this, 'create_field_submit'] to at least rule that out – Clive Aug 1 '17 at 8:41
0

If this is not working, then the reason for this is, that the block plugin is not the form class. This is BlockForm, which calls the methods in the plugin while building, validating and submitting the form. So if you want to add custom code to the submit in a block plugin override:

public function blockSubmit($form, FormStateInterface $form_state) {}

This code will then be included when the form class calls submitConfigurationForm().

If you have more than one submit button you can check the triggering element in $form_state.


Edit:

Another option is to use a static submit function instead of the class method.

0

'::create_field_submit' doesn't mean use the create_field_submit() method of the class containing the code I am using. For FormState::prepareCallback(), the method handling such handlers, it means Use the create_field_submit() method of the object returned from FormState::getFormObject().

public function prepareCallback($callback) {
  if (is_string($callback) && substr($callback, 0, 2) == '::') {
    $callback = [$this->getFormObject(), substr($callback, 2)];
  }
  return $callback;
}

Given that FormState::getFormObject() declares its returned value to be an object implementing \Drupal\Core\Form\FormInterface, this limits its possible usage to few classes, which doesn't include a block plugin, which doesn't implement that interface.

As Clive said, try with [$this, 'create_field_submit'], and see if it works.

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.