<?php

namespace Drupal\my_custom_module\Controller;

use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\TempStore\PrivateTempStoreFactory;

/**
* Class ProductSelectAjaxController.
*
* @package Drupal\beazly_core\Controller
*/
class MyCustomSelectAjaxController extends ControllerBase {

 /**
  * Drupal\Core\TempStore\PrivateTempStoreFactory definition.
  *
  * @var \Drupal\Core\TempStore\PrivateTempStoreFactory
  */
 protected $tempStore;


 /**
  * Drupal\Core\Entity\EntityTypeManagerInterface;
  *
  * @var \Drupal\Core\Entity\EntityTypeManagerInterface;
  */
 protected $entityTypeManager;

 /**
  *
  */
 public function __construct(PrivateTempStoreFactory $temp_store_factory, EntityTypeManagerInterface $entityTypeManager) {
   $this->tempStore = $temp_store_factory->get('my_custom_module');
   $this->entityTypeManager = $entityTypeManager->getStorage('node');
 }

 /**
  *
  */
 public static function create(ContainerInterface $container) {
   return new static(
     $container->get('tempstore.private'),
      $container->get('entity_type.manager')
   );
 }

 /**
  * Filter dropdown for the product page.
  */
 public function filterselectlist($cat_id) {

   $response = new AjaxResponse();

   // Setting the selector for the product filter.
   $selector = '#second-filter';
   $options = '';

   // Setting the currently selected value which was selected dyanmically.
   $this->tempStore->set('selected', $cat_id);

   $query = $this->entityTypeManager->getQuery();
   $samples_by_cat_id = $product_query->condition('type', 'samples')
     ->condition('field_my_category', $cat_id,)
     ->execute();

   $sample_nodes = $this->entityTypeManager->loadMultiple($samples_by_cat_id);

   $options = "<option value='Any'>" . t('Select any item'). "</option>";

   if ($sample_nodes) {
     foreach ($sample_nodes as $node) {
       $options .= "<option value='" . $node->id() . "'>" . $node->label() . "</option>";
     }
   }

   $select_list = "<select id='second--filter' name='nid' class='form-select form-control'
       data-drupal-selector='second-product-filter' > " . $options . " </select>";

   $response->addCommand(new ReplaceCommand($selector, $select_list));

   return $response;

 }