Running in real troubles with our products? Get in touch with our Support Team 👉

0
No products in the cart.
  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #9897
    mudassar-rehman
    Participant

    To render an enabled CMS block in a phtml file in Magento 2, you can use the following code:

    <?php
    $blockId = 'your_block_identifier'; // Replace with your block identifier
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $block = $objectManager->create('Magento\Cms\Block\Block')->setBlockId($blockId);
    if ($block->getIsActive()) {
        echo $block->toHtml();
    }
    ?>
    

    Here’s a breakdown of the code:

    Define the identifier of the CMS block you want to render. This can be found in the CMS block list in the Magento admin panel.

    $blockId = 'your_block_identifier';
    

    Create an instance of the CMS block using the ObjectManager

    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $block = $objectManager->create('Magento\Cms\Block\Block')->setBlockId($blockId);
    

    Check if the block is active (enabled)

    if ($block->getIsActive()) {
    

    If the block is active, render the block’s HTML using the toHtml() method.

    echo $block->toHtml();
    

    Note that using the ObjectManager directly is not best practice, and it is recommended to use dependency injection instead. Additionally, you should make sure to sanitize the $blockId input to avoid security vulnerabilities.

    #9896
    vidya-sagar
    Participant

    Pretty much what the title says. I want to add the google map in a cms block and then call it in a form.phtml for Contact Page. How do I do it?

    #9898
    brinda
    Participant

    Override form.phtml file in your child theme and then Call your static block in that override form.phtml file:

    <?php 
    echo $this->getLayout()
    ->createBlock('Magento\Cms\Block\Block')
    ->setBlockId('your_block_identifier')
    ->toHtml();
    ?>
    
Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.