How to include a new field on the Shipment API in Magento2

Create a new field on the sales shipment table using the db-schema.xml file

Then add the newfield on the extension attributes file

app/code/JJ/DocumentNumber/etc

extension_attributes.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework/Extension/etc/extension_attributes.xsd">
	<extension_attributes for="MagentoSalesApiDataShipmentCreationArgumentsInterface">
		<attribute code="document_number" type="string"/>
	</extension_attributes>
</config>

For saving the field

di.xml

<config xsi:noNamespaceSchemaLocation="urn:magento:framework/ObjectManager/etc/config.xsd">
  <type name="MagentoSalesApiShipmentRepositoryInterface">
    <plugin name="custom_shipment_repository_plugin" type="JJDocumentNumberPluginShipmentRepositoryPlugin"/>
  </type>
 </config>

ShipmentRepositoryPlugin.php

<?php
namespace JJDocumentNumberPlugin;

use MagentoSalesApiDataShipmentExtensionFactory;
use MagentoSalesApiDataShipmentInterface;
use MagentoSalesApiShipmentRepositoryInterface;

class ShipmentRepositoryPlugin
{
  private $extensionFactory;

  public function __construct(ShipmentExtensionFactory $extensionFactory)
  {
    $this->extensionFactory = $extensionFactory;
  }

  public function afterGet(
    ShipmentRepositoryInterface $subject,
    ShipmentInterface $shipment
  ) {
    $extensionAttributes = $shipment->getExtensionAttributes();
    if ($extensionAttributes === null) {
      $extensionAttributes = $this->extensionFactory->create();
    }

    $customField = $shipment->getData('document_number'); // Fetch the value
    $extensionAttributes->setDocumentNumber($customField);
    $shipment->setExtensionAttributes($extensionAttributes);

    return $shipment;
  }

  public function afterGetList(
    ShipmentRepositoryInterface $subject,
    $searchResult
  ) {
    foreach ($searchResult->getItems() as $shipment) {
      $this->afterGet($subject, $shipment);
    }
    return $searchResult;
  }

   public function beforeSave(
    ShipmentRepositoryInterface $subject,
    ShipmentInterface $shipment
  ) {
    $extensionAttributes = $shipment->getExtensionAttributes();
    if ($extensionAttributes && $extensionAttributes->getDocumentNumber()) {
      $shipment->setData('document_number', $extensionAttributes->getDocumentNumber());
    }
    return [$shipment];
  }
}

Leave a comment

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