Created
April 12, 2023 06:57
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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