Get All CMS static block using GraphQl in Magento 2 by a simple module.
We can get all the CMS Static block collection by GraphQl by just create a Resolver file and add our custom logic for getting all the CMS Static block collection.
If you want to know Out of the Box Magento cmsBlocks
Query, Refer a link with more explanation, Cms Page, and Cms Blocks GraphQL Query in Magento.
You can add the filter to the condition for getting specific CMS Static block also in the Resolver PHP file.
I hope you are aware of What is GraphQl and how GraphQL is used for the programming language like Magento 2 If You are new to GraphQL check the link for GraphQl in Magento 2.
Now we can start the module using Magento 2 for fetch all the CMS Static Block using GraphQl Query.
You need to create the first registration.php and module.xml file for defining our module.
I have taken Packagename as Rbj and Modulename as CmsBlocksGraphQl.
Path: app/code/Rbj/CmsBlocksGraphQl/registration.php
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Rbj_CmsBlocksGraphQl', __DIR__ );
Create module.xml file, Path: app/code/Rbj/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="Rbj_CmsBlocksGraphQl"> <sequence> <module name="Magento_Cms"/> <module name="Magento_GraphQl"/> </sequence> </module> </config>
Our Module depends on GraphQL and CMS Module so we have given the dependency on the module.xml
file for each module.
Every GraphQl Module must contain schema.graphqls file under the etc folder of a module.
schema.graphqls is at the center of any GraphQL Query implementation and describes what data can be queried. So You can define your query data basic skeleton under the schema.graphqls file.
Path : app/code/Rbj/CmsBlocksGraphQl/etc/schema.graphqls
type Query { cmsBlocks: CmsBlocks @resolver(class: "Rbj\\CmsBlocksGraphQl\\Model\\Resolver\\CmsBlock") @doc(description: "Get all the CMS Static blocks from store.") } type CmsBlocks @doc(description: "Cms Blocks graphql gather Data of all static block information") { allBlocks: [BlockRecord] @doc(description: "An array containing the all the CMS static block from Magento") } 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") }
Now Create a Resolver Model for our custom module.
Rbj\\CmsBlocksGraphQl\\Model\\Resolver\\CmsBlock
CmsBlock Resolver Model class which is defined in schema.graphql file at above. In this Model, resolve() method will simply return data of all the CMS static block.
Path: app/code/Rbj/CmsBlocksGraphQl/Model/Resolver/CmsBlock.php
<?php declare(strict_types=1); namespace Rbj\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; } }
Now Run Upgrade command to install our module.
php bin/magento setup:upgrade php bin/magento cache:flush
You can check your GraphQL query response by installing chrome extension ChromeiQL or Altair GraphQL addon.
Check Result Using ChromeiQl by,
In Request Body, You need to pass required data(field) to request payload for getting response of CMS Static Block
{ cmsBlocks { allBlocks { name identifier content } } }
The result will be graphQl Response,
{ "data": { "cmsBlocks": { "allBlocks": [ { "name": "Contact us info", "identifier": "contact-us-info", "content": "<div class=\"contact-info cms-content\">\r\n<p class=\"cms-content-important\">We love hearing from you, our Luma customers. Please contact us about anything at all.</div>" }, { "name": "Block 2", "identifier": "block_2", "content": "<p>block 2 block </p>" }, { "name": "Footer Links Block", "identifier": "footer_links_block", "content": "<ul class=\"footer links\">\r\n<li class=\"nav item\"><a href=\"{{store url=\"about-us\"}}\">About us</a></li>\r\n<li class=\"nav item\"><a href=\"{{store url=\"customer-service\"}}\">Customer Service</a></li>\r\n</ul>" } ] } } }