how to do ajax callback in custom block, which will fetch records from database dynamically in Drupal 10?

17 Views Asked by At

I have created custom module to load records dynamically with Ajax callback in custom block in drupal 10.2. But Ajax callback does not work in custom block, where callback function is written on same custom block file, please see the code below,

namespace Drupal\my_module\Plugin\Block;

use Drupal\Core\Block\BlockBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Database\Connection;

/**
 * Provides a custom block with AJAX functionality.
 *
 * @Block(
 *   id = "my_custom_block",
 *   admin_label = @Translation("My Custom Block"),
 * )
 */
class MyCustomBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    $build = [];

   $build['button'] = [
      '#type' => 'button',
      '#value' => $this->t('Fetch Records'),
      '#id' => 'fetch-records-button',
      '#ajax' => [
        'callback' => '::ajaxCallback',
        'event' => 'click',
      ],
      '#prefix' => '<div id="my-custom-block-wrapper">',
      '#suffix' => '</div>',
    ];

    return $build;
  }

  /**
   * AJAX callback function.
   */
  public function ajaxCallback(array &$form, FormStateInterface $form_state) {
    // Perform a database query.
    $database = \Drupal::database();
    $query = $database->query("SELECT search,COUNT(*) AS count, url FROM `search_tracking` GROUP BY search ORDER BY count DESC");
    $result = $query->fetchAll();
    \Drupal::service('page_cache_kill_switch')->trigger();

    // Build the HTML for the query result.
    $output = '<ul>';
    foreach ($result as $row) {
      $output .= '<li>' . $row->title . '</li>';
    }
    $output .= '</ul>';

    return [
      '#type' => 'markup',
      '#markup' => $output,
    ];
  }

}

Can you please help to get result on ajax callback?

Thanks you in advance.

0

There are 0 best solutions below