I'm working on a site that needs a certain feature gated by a simple form containing a single email field:

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['email_intro'] = [
      '#markup' => '<p>Please enter your email to begin.',
    $form['email'] = [
      '#type' => 'textfield',
      '#maxlength' => 128,
      '#size' => 64,
      '#weight' => '0',
    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit'),
      '#ajax' => [
        'callback' => [$this, 'myCallback'],
        'event' => 'click',

    return $form;

The callback makes an API call and, if their email is successfully inserted/updated, they can proceed.

public function myCallback(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    // Omitted some code that uses a custom service to make a call to an API
    if($apiResponse->status === 'success') {
        $response->addCommand(); // Need help here
    return $response;

I'd like to bind a click event to some elements on the page that will open a dialog if the response is a success but I'm having trouble figuring out how to do this.

These elements work if I load the page with class="use-ajax" and the href set but I can't figure out how to dynamically add this functionality.

Thank you for the help!

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.