Get Cms Blocks collection using Graphql Magento 2.

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 Resolver file and add our custom logic for getting all the CMS Static block collection. You can add filter to the condition for getting specific CMS Static block also in Resolver php file.

I hope you are aware of What is GraphQl and how GraphQL are used for the programming language like Magento 2 If You are new to GraphQL check 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 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

Create module.xml file, Path: app/code/Rbj/CmsBlocksGraphQl/etc/module.xml

Our Module depends on GraphQL and CMS Module so we have given dependency on 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 the 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

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

Now Run Upgrade command to install our module.

You can check your GraphQL query response by installing chrome extension ChromeiQL or Altair GraphQL addon.

Check Result Using ChromeiQl by,

graphql cms blocks
Cms Block Graphql Magento 2

 

In Request Body, You need to pass required data(field) to request payload for getting response of CMS Static Block

The result will be graphQl Response,

 

Leave a Reply

Your email address will not be published. Required fields are marked *