To call a static block into a GraphQL query in the Alpine.js

 To call a static block into a GraphQL query in the Alpine.js framework within Magento 2, you would need to follow these steps:

  1. Create a GraphQL query:

    • Define your query in the app/code/{Vendor}/{Module}/etc/graphql/schema.graphqls file. For example:

      graphql
      type Query { staticBlock(identifier: String!): String @resolver(class: "{Vendor}\{Module}\Model\Resolver\StaticBlock") @doc(description: "Retrieve the content of a static block by identifier") }
  2. Create a Resolver class:

    • Create the resolver class app/code/{Vendor}/{Module}/Model/Resolver/StaticBlock.php. In this class, you will define the logic to retrieve the static block content. Here’s an example implementation:

      php
      <?php namespace {Vendor}{Module}ModelResolver; use MagentoCmsModelBlockRepository; use MagentoFrameworkExceptionNoSuchEntityException; use MagentoFrameworkGraphQlQueryResolverInterface; use MagentoFrameworkGraphQlQueryResolverContextInterface; class StaticBlock implements ResolverInterface { private $blockRepository; public function __construct(BlockRepository $blockRepository) { $this->blockRepository = $blockRepository; } public function resolve( ContextInterface $context, array $args, array $directives = [], GraphQLTypeDefinitionResolveInfo $info = null ) { $identifier = $args['identifier']; try { $block = $this->blockRepository->getByIdentifier($identifier); return $block->getContent(); } catch (NoSuchEntityException $e) { return null; } } }
  3. Utilize the GraphQL query in Alpine.js:

    • In your Alpine.js component, make an HTTP request to the GraphQL endpoint to fetch the static block content. Here’s an example using Axios:

      javascript
      <template> <div x-data="{ blockContent: '' }"> <div x-html="blockContent"></div> </div> </template> <script> import axios from 'axios'; export default { mounted() { axios.post('/graphql', { query: ` query { staticBlock(identifier: "your_block_identifier") } `, }) .then(response => { this.blockContent = response.data.data.staticBlock; }) .catch(error => { console.error(error); }); }, } </script>

Ensure to replace {Vendor} and {Module} with your actual vendor and module names, respectively. Also, replace "your_block_identifier" with the identifier of the static block you want to retrieve.

Remember to adjust the code according to your specific requirements and ensure that you have appropriate permissions and configurations set up for GraphQL and the Alpine.js framework in your Magento 2 installation.

Puneet Kumar Magento Developer
0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply