Skip to content

Instantly share code, notes, and snippets.

@binnyaxel
Created August 18, 2022 05:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save binnyaxel/b2c886001ca86dd78cf61f6143d13ac5 to your computer and use it in GitHub Desktop.
Save binnyaxel/b2c886001ca86dd78cf61f6143d13ac5 to your computer and use it in GitHub Desktop.
MyCustomModuleAjaxFilterController
<?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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment