How does the #submit property works with #ajax?

by Eria   Last Updated January 12, 2018 13:07 PM

I'm having trouble understanding how works the #submit property of a submit element in Drupal 8, when Ajax is used.

I found this code, as an example :

There is a submit button in the form, described by the code below :

$form['container']['actions']['add_item'] = [
  '#type'   => 'submit',
  '#value'  => $this->t('Add another name'),
  '#submit' => ['::MYMODULE_MYFORM_add_item'],
  '#ajax'   => [
    // Could also use [ $this, 'colorCallback'].
    'callback' => '::MYMODULE_MYFORM_ajax_callback',
    'wrapper'  => 'my-container', // CHECK THIS ID

There are 2 callback functions used here : the value of the #submit property and the value of callback in the #ajax property.

What happens exactly when the user clicks on the button ? As I understand it, MYMODULE_MYFORM_add_item function is first called, then MYMODULE_MYFORM_ajax_callback function.

But, in a custom module, I'm currently doing something like this :

function mymodule_form_user_register_form_alter(&$form, FormStateInterface $form_state, $form_id) {

    $form['account']['fill_username'] = array(
        '#type' => 'submit',
        '#value' => t('Fill username with Bob'),
        '#weight' => -1,
        '#submit' => ['mymodule_fill_username_submit'],
        '#ajax' => array(
            'callback' => 'mymodule_fill_username_callback',
            'wrapper' => 'edit-account'

function mymodule_fill_username_submit( $form, FormStateInterface &$form_state ){
    $form_state->setValue('name', 'Bob');
    $form_state->setRebuild( true );

function mymodule_fill_username_callback( $form, FormStateInterface &$form_state ){
    return $form['account'];

The aim is to inject a value in the "Username" field, just to try and understand how this works.

As I click on the button, mymodule_fill_username_callback is called (I see the log) but mymodule_fill_username_submit never. And, of course, the field is not filled at all...

I don't understand what happens here. Nor how it's supposed to work.

Can anybody help ?

Tags : 8 forms ajax

Related Questions

Access Denied when Menu CallBack Function is Called

Updated April 20, 2015 06:03 AM