0

I have added a block which shows the no of items added to an entity. I want to refresh the block through ajax as the items are added to an entity through ajax form so whenever I add an item, it will refresh or re-render the block content too.

I found some of the modules, but they are in Drupal 7 and not available for D8 so I want to make it done with my custom module but didn't find anything useful.

UPDATED

I have added the class attribute with the block and whenever I add any items, I made an ajax request through javascript which calls the respective controller and at the same time, I run this too--

// This is a part of the controller function from where I am calling below defined methods.
$this->updateBlock();

protected function getBlock() {
    $block = $this->blockManager->createInstance('block_id', []);
    return $block;
}

public function updateBlock() {
    $block = $this->getBlock();
    $this->response->addCommand(new ReplaceCommand('.block--class', $block->build()));
    return $this->response;

}

But It is not updating the block.

0

Important part you left out is what kind of ajax, is it a form you are submitting or custom javascript which uses ajax to target a controller endpoint? As this is how we return the code of the block.

But the code you are looking for re-rendering a block is:

$id = '' // the number of the block_id
$block = \Drupal\block_content\Entity\BlockContent::load($id);
$render = \Drupal::entityTypeManager()->getViewBuilder('block_content')->view($block);
return $render;
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.