0

I'm working on a payment gateway, so I've created a BasePaymentOffsiteForm form where I'm trying to make an ajax callback, but it is not working. Can you help me to know what is wrong with my code?

    $form = parent::buildConfigurationForm($form, $form_state);

    $form['content'] = [
      '#type' => 'container',
      '#prefix' => '<div id="validate-phone-number">',
      '#suffix' => '</div>',
    ];

    $form['content']['mobile_phone'] = [
      '#type'   => 'textfield',
      '#title'  => $this->t('Mobile phone'),
    ];

    $form['content']['validate_client'] = [
      '#type' => 'button',
      '#value' => $this->t('Validate Client'),
      '#ajax' => [
        '#callback' => [get_class($this), 'clientValidateForm'],
        'event' => 'click',
        'wrapper' => 'validate-phone-number',
      ],
    ];

    $form['content']['cancel'] = [
      '#type' => 'link',
      '#title' => $this->t('Cancel'),
      '#url' => Url::fromUri($form['#cancel_url']),
    ];


    return $form;
  }

  public static function clientValidateForm(array $form, FormStateInterface $form_state) {
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => 'Pay',
    ];
    return $form['submit'];
  }

It never gets in cientValidateForm method.

1
  • 2
    You have to add any form elements in the form definition. They cannot be added in the ajax callback.
    – Jaypan
    Jun 16 '20 at 1:10
1

You're never making it to your callback because you don't have your #ajax array defined correctly, callback should not be defined as a hashed key. Take a look at the Adding an AJAX event example on d.o.

This should work:

$form['content']['validate_client'] = [
  '#type' => 'button',
  '#value' => $this->t('Validate Client'),
  '#ajax' => [
    // Change the callback key and update your callback value.
    'callback' => [$this, 'clientValidateForm'],
    'event' => 'click',
    'wrapper' => 'validate-phone-number',
  ],
];

Also note that Jaypan is right, you can't define new elements in your validation callback so you'll have to change that too. You may want to set a $form_state value in your validation handler and use that to add your element inside your build method. You may also need to update the wrapper value in your #ajax definition to align with the other changes.

2
  • Thank you, it worked for me, I just add the # in callback index just for testing, but the use of $this without get_class was the solution. Jun 18 '20 at 13:19
  • Awesome! Feel free to mark this answer is accepted if it solved your problem.
    – sonfd
    Jun 18 '20 at 13:44

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.