2

The only post I've found about this question is sadly unanswered, so here's my situation.

I have a custom form that I made in MyModule. On the send button, I set an ajax call that loads a list of entities. This works fine.

My problem : In that entities list, at the end, I add a "load more" button. I'd like to add an ajax call on it to load more entities, but the ajax callback is never called. I guess it's because it's in another class, but I can't figure out how to fix this. If you need more precision, please ask. Thank you!

Form

namespace Drupal\MyModule\Form;    
use Drupal\MyModule\FormatDbQueryResults;

class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {

    // [...] Stuff

    $form['actions']['send'] = [
      '#type' => 'submit',
      '#value' => 'Search',
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];
    return $form;
  }

  public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
    $response = new AjaxResponse();
    $output = new FormatDbQueryResults();
    $value = $output->getFormattedContent($form_state->getValues(), 1);
    $response->addCommand(new ReplaceCommand('#results', $value));
    return $response;
  }

}

An other class in the same module

namespace Drupal\MyModule;   

class FormatDbQueryResults {

  public function getFormattedContent($form_values, $loadMoreIndex) {

    // [...] Database EntityQuery stuff

    // 
    // MY PROBLEMS ARE HERE
    // 
    // The callback is never called. 
    // Also, I would need to send parameters to that callback
    $output['load_more'] = array(
      '#type' => 'button',
      '#value' => 'More',
      '#ajax' => [
        'callback' => 'loadMoreEntities',
        'event' => 'click',
      ],
    );
    return $output;
  }

  public function loadMoreEntities($form_values, $loadMoreIndex) {
    $response = new AjaxResponse();
    $value = $this->getFormattedContent($form_values, $loadMoreIndex++);
    $response->addCommand(new AppendCommand('#results', $value));
    return $response;
  }
}

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.