How To

Magento 2: How to Get Custom Column Value of Shipment using GraphQL

Hello Magento Friends,

In today’s blog, we will learn about How to Get Custom Column Value of Shipment using GraphQL in Magento 2.

In Magento 2, shipments represent the process of delivering orders to customers. While Magento offers a plethora of default attributes for shipments, there are instances where merchants need to include custom data fields to streamline their logistics or integrate with third-party systems. These custom columns could contain information such as delivery instructions, special packaging requirements, or additional tracking details.

Now, let’s dive into the practical aspect of accessing custom column values of shipments using GraphQL in Magento 2. 

Steps to Get Custom Column Value of Shipment using GraphQL in Magento 2:

Step 1: First, we need to create “schema.graphqls” file inside the etc folder.

app\code\Vendor\Extension\etc\

Then add the code as follows

type Query {
    customerOrders: CustomerOrders @resolver(class: "Magento\\SalesGraphQl\\Model\\Resolver\\Orders") @deprecated(reason: "Use the `customer` query instead.") @cache(cacheable: false)
}

type CustomerOrders @doc(description: "The collection of orders that match the conditions defined in the filter.") {
    items: [CustomerOrder]! @doc(description: "An array of customer orders.")
    page_info: SearchResultPageInfo @doc(description: "Contains pagination metadata.")
    total_count: Int @doc(description: "The total count of customer orders.")
}
type CustomerOrder  { 
      shipments: [OrderShipment] @doc(description: "A list of shipments for the order.") @resolver(class: "Vendor\\Extension\\Model\\Resolver\\Shipments")
}
type OrderShipment @doc(description: "Contains shipment details.") {
   custom_fee: Float  @deprecated(reason: "Use the `custom_fee` field instead.")
}

Step 2: After that, we must create a “Shipments.php” file inside the Resolver folder.

app\code\Vendor\Extension\Model\Resolver\

And add the code as given below

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */declare(strict_types=1);

namespace Vendor\Extension\Model\Resolver;

use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\GraphQl\Config\Element\Field;
use Magento\Framework\GraphQl\Query\ResolverInterface;
use Magento\Framework\GraphQl\Schema\Type\ResolveInfo;
use Magento\Sales\Api\Data\ShipmentInterface;
use Magento\Sales\Model\Order;

/**
 * Resolve shipment information for order
 */class Shipments implements ResolverInterface
{
    /**
     * @inheritDoc
     */    public function resolve(Field $field, $context, ResolveInfo $info, array $value = null, array $args = null)
    {
        if (!isset($value['model']) && !($value['model'] instanceof Order)) {
            throw new LocalizedException(__('"model" value should be specified'));
        }
        /** @var Order $order */        $order = $value['model'];
        $shipments = $order->getShipmentsCollection()->getItems();

        if (empty($shipments)) {
            //Order does not have any shipments
            return [];
        }

        $orderShipments = [];
        foreach ($shipments as $shipment) {
            $orderShipments[] =
                [
                    'id' => base64_encode($shipment->getIncrementId()),
                    'number' => $shipment->getIncrementId(),
                    'comments' => $this->getShipmentComments($shipment),
                    'custom_fee' => $shipment->getCustomFee(),
                    'model' => $shipment,
                    'order' => $order
                ];
        }
        return $orderShipments;
    }

    /**
     * Get comments shipments in proper format
     *
     * @param ShipmentInterface $shipment
     * @return array
     */    private function getShipmentComments(ShipmentInterface $shipment): array
    {
        $comments = [];
        foreach ($shipment->getComments() as $comment) {
            if ($comment->getIsVisibleOnFront()) {
                $comments[] = [
                    'timestamp' => $comment->getCreatedAt(),
                    'message' => $comment->getComment()
                ];
            }
        }
        return $comments;
    }
}

Step 3: At last run the upgrade command and compile command then pass the query like below in the server

{
  customerOrders {
    items {
      order_number
      id
      shipments{
      custom_fee
      }
      
    }
  }
}

Output:

Conclusion:

This way you can retrieve the custom column value of shipment using GraphQL in Magento 2. If you have any doubts, share them with me through the comment section and I will be quick to provide you with a solution. Share the article with your friends, and stay in touch with us for more such Magento 2 tutorials.

Also learn-

Magento 2: How to Get Custom Column Value of Invoice and Credit Memo using GraphQL

Magento 2: How to Get Custom Column Value of Order using GraphQL

Happy Coding!

Click to rate this post!
[Total: 0 Average: 0]
Dhiren Vasoya

Dhiren Vasoya is a Director and Co-founder at MageComp, Passionate ?️ Certified Magento Developer?‍?. He has more than 9 years of experience in Magento Development and completed 850+ projects to solve the most important E-commerce challenges. He is fond❤️ of coding and if he is not busy developing then you can find him at the cricket ground, hitting boundaries.?

Recent Posts

Upgrade Your E-commerce Store with Magento 2 Hyvä Theme

Magento 2 Hyvä Theme is quickly becoming a popular choice among e-commerce businesses for its…

21 hours ago

A Complete Guide of Hyvä Themes

In the rapidly evolving world of e-commerce, the success of an online store greatly hinges…

22 hours ago

Magento 2: How to Add Custom Button to Download Custom Created PDF Programmatically in Admin Sales Order View

Hello Magento Friends, Ever wanted to provide admins with a quick way to download custom…

22 hours ago

Mastering Tailwind CSS in Laravel: A Comprehensive Guide

Tailwind CSS has emerged as a powerful utility-first CSS framework, offering developers a unique approach…

6 days ago

React Native or Flutter in 2024

The mobile app development field has witnessed a rapid revolution over the past few years.…

1 week ago

Magento 2: How To Call JS on the Checkout Page?

Hello Magento mates, Today we will learn to add a call JS on the checkout…

2 weeks ago