PHP code example of hyva-themes / magento2-graphql-view-model

1. Go to this page and download the library: Download hyva-themes/magento2-graphql-view-model library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

hyva-themes / magento2-graphql-view-model example snippets


<?= $gqlViewModel->query("product_list_query", "
products(filter: {} pageSize: 20) {
  items {
    {$type}_products {
        sku
        id
        small_image {
          url
        }
    }
  }
}", ['type' => $type])


public function execute(Observer $event)
{
    $gqlEditor = new GraphqlQueryEditor(); // or use dependency injection
    
    $queryString = $event->getData('gql_container')->getData('query');
    $linkType  = $event->getData('type');
    $path  = ['products', 'items', ($linkType ? "{$linkType}_products" : 'products'), 'small_image'];
    
    // add a single field to a result object
    $queryString = $gqlEditor->addFieldIn($queryString, $path, 'url_webp');
    
    // add multiple fields to a result object
    $queryString = $gqlEditor->addFieldIn($queryString, ['products', 'items', 'products', 'image'], 'label url_webp');
    
    // add a query argument
    $queryString = $gqlEditor->addArgumentIn($queryString, ['products', 'filter', 'name'], 'match', 'Tank');
    $queryString = $gqlEditor->addArgumentIn($queryString, ['products'], 'pageSize', 2);
    
    // set updated query back on container
    $event->getData('gql_container')->setData('query', $queryString);
}

$gqlEditor->addFieldIn($queryString, ['products', 'items', 'products', 'small_image'], 'label url_webp')