Magento 2 Get CMS Blocks Collection Using GraphQL

In Magento 2, we can get all the CMS static block collection using custom GraphQl module.

We need to create a resolver file and write our custom logic to fetch all the CMS static blocks collection. We can add the filter to the condition for getting specific CMS static blocks also in the resolver PHP file.

Let’s start to create our custom module:

Step 1: First we need to create the registration.php and module.xml files to define the module registration Magento environment.

Lets assume our Package Name is Magemeta and Module Name as CmsBlocksGraphQl.

Path: app/code/Magemeta/CmsBlocksGraphQl/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Magemeta_CmsBlocksGraphQl',
    __DIR__
);

Create module.xml file on following path:

Path: app/code/Magemeta/CmsBlocksGraphQl/etc/module.xml

<?xml version="1.0"?>
 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Magemeta_CmsBlocksGraphQl">
        <sequence>
            <module name="Magento_Cms"/>
            <module name="Magento_GraphQl"/>
        </sequence>
    </module>
</config>

We have declared the dependencies on GraphQL and CMS modules in the module.xml file.

Every GraphQl module must contain schema.graphqls file in the etc folder of a module.

schema.graphqls explains the GraphQL query implementation and describes what data can be queried in the query where we can define our custom query data in the schema.graphqls file.

Path: app/code/Magemeta/CmsBlocksGraphQl/etc/schema.graphqls

type Query {
    cmsBlocks: CmsBlocks @resolver(class: "Magemeta\\CmsBlocksGraphQl\\Model\\Resolver\\CmsBlock") @doc(description: "Get all the CMS static blocks from store")
}
 
type CmsBlocks @doc(description: "Cms blocks Graphql collects data of all the static block information") {
    allBlocks: [BlockRecord] @doc(description: "An array containing all the CMS static block")
}
 
type BlockRecord {
    identifier: String @doc(description: "Identifier of CMS static block")
    name: String @doc(description: "Get name of CMS static block")
    content: String @doc(description: "Content of CMS static block")
}

Next we need to create a resolver model for our custom module.

CmsBlock resolver model class is defined in schema.graphql file where resolve() method will return data of all the CMS static blocks.

Path: app/code/Magemeta/CmsBlocksGraphQl/Model/Resolver/CmsBlock.php

<?php
declare(strict_types=1);
 
namespace Magemeta\CmsBlocksGraphQl\Model\Resolver;
 
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Exception\GraphQlInputException;
use Magento\Framework\GraphQl\Exception\GraphQlNoSuchEntityException;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
 
/**
 * Cms Static Block resolver
 */
class CmsBlock implements ResolverInterface
{
    public function __construct(
        \Magento\Cms\Api\BlockRepositoryInterface $blockRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
    ) {
        $this->blockRepository = $blockRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
    }
 
    /**
     * @inheritdoc
     */
    public function resolve(
        Field $field,
        $context,
        ResolveInfo $info,
        array $value = null,
        array $args = null
    ) {
        $blocksData = $this->getBlocksData();
        return $blocksData;
    }
 
    /**
     * @return array
     * @throws GraphQlNoSuchEntityException
     */
    private function getBlocksData(): array
    {
        try {
            /* filter for all the pages */
            $searchCriteria = $this->searchCriteriaBuilder->addFilter('block_id', 1,'gteq')->create();
            $blocks = $this->blockRepository->getList($searchCriteria)->getItems();
            $cmsBlocks['allBlocks'] = [];
            foreach($blocks as $block) {
                $cmsBlocks['allBlocks'][$block->getId()]['identifier'] = $block->getIdentifier();
                $cmsBlocks['allBlocks'][$block->getId()]['name'] = $block->getTitle();
                $cmsBlocks['allBlocks'][$block->getId()]['content'] = $block->getContent();
            }
        } catch (NoSuchEntityException $e) {
            throw new GraphQlNoSuchEntityException(__($e->getMessage()), $e);
        }
        return $cmsBlocks;
    }
}

Next we need to run setup:upgrade command to install our custom module.

php bin/magento setup:upgrade
php bin/magento cache:flush

We can also check our GraphQL query response by installing chrome extension ChromeiQL or Altair GraphQL addon.

Request Payload:

{
  cmsBlocks {
    allBlocks {
      name
      identifier
      content
    }
  }
}

Response:

{
  "data": {
    "cmsBlocks": {
      "allBlocks": [
        {
          "name": "Contact Us",
          "identifier": "contact-us",
          "content": "<div class=\"contact-info cms-content\">\r\n<p class=\"cms-content-important\">We are happy to help you anyway. Please contact us for you queries.</div>"
        },
        {
          "name": "Test Block 2",
          "identifier": "block_2",
          "content": "<p>Block 2 test content</p>"
        }
      ]
    }
  }
}

Leave a Reply