Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Created April 12, 2023 06:57
Show Gist options
  • Save prashantdsala/2b343cbf774992c1c8bfeb82a4c1d26d to your computer and use it in GitHub Desktop.
Save prashantdsala/2b343cbf774992c1c8bfeb82a4c1d26d to your computer and use it in GitHub Desktop.
Drupal - Snippet to programatically return a block as a response to AJAX request from controller
<?php
use Drupal\Core\Render\Renderer;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Form\FormBuilder;
/**
* Drupal\Core\Block\BlockManager definition.
*
* @var \Drupal\Core\Block\BlockManager
*/
protected $pluginManagerBlock;
/**
* Constructor.
*/
public function __construct(Renderer $renderer, FormBuilder $formBuilder, BlockManager $pluginManagerBlock) {
$this->renderer = $renderer;
$this->pluginManagerBlock = $pluginManagerBlock;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('renderer'),
$container->get('plugin.manager.block'),
);
}
$config = [];
$plugin_block = $this->pluginManagerBlock->createInstance('your_block_machine_name', $config);
// Some blocks might implement access check.
//$access_result = $plugin_block->access(\Drupal::currentUser());
// Return empty render array if user doesn't have access.
// $access_result can be boolean or an AccessResult class
// if (is_object($access_result) && $access_result->isForbidden() || is_bool($access_result) && !$access_result) {
// // You might need to add some cache tags/contexts.
// return [];
// }
$html = $plugin_block->build();
// Add the cache tags/contexts.
$this->renderer->addCacheableDependency($html, $plugin_block);
$ajax_response = new AjaxResponse();
$target = "HTML class or id name";
$ajax_response->addCommand(new HtmlCommand($target, $html));
return $ajax_response;
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment