Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
AddTrack.php
Go to the documentation of this file.
1 <?php
8 
10 
12 {
18  const ADMIN_RESOURCE = 'Magento_Sales::shipment';
19 
23  protected $shipmentLoader;
24 
29  public function __construct(
30  Action\Context $context,
31  \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader $shipmentLoader
32  ) {
33  $this->shipmentLoader = $shipmentLoader;
34  parent::__construct($context);
35  }
36 
43  public function execute()
44  {
45  try {
46  $carrier = $this->getRequest()->getPost('carrier');
47  $number = $this->getRequest()->getPost('number');
48  $title = $this->getRequest()->getPost('title');
49  if (empty($carrier)) {
50  throw new \Magento\Framework\Exception\LocalizedException(__('Please specify a carrier.'));
51  }
52  if (empty($number)) {
53  throw new \Magento\Framework\Exception\LocalizedException(__('Please enter a tracking number.'));
54  }
55  $this->shipmentLoader->setOrderId($this->getRequest()->getParam('order_id'));
56  $this->shipmentLoader->setShipmentId($this->getRequest()->getParam('shipment_id'));
57  $this->shipmentLoader->setShipment($this->getRequest()->getParam('shipment'));
58  $this->shipmentLoader->setTracking($this->getRequest()->getParam('tracking'));
59  $shipment = $this->shipmentLoader->load();
60  if ($shipment) {
61  $track = $this->_objectManager->create(
62  \Magento\Sales\Model\Order\Shipment\Track::class
63  )->setNumber(
64  $number
65  )->setCarrierCode(
66  $carrier
67  )->setTitle(
68  $title
69  );
70  $shipment->addTrack($track)->save();
71 
72  $this->_view->loadLayout();
73  $this->_view->getPage()->getConfig()->getTitle()->prepend(__('Shipments'));
74  $response = $this->_view->getLayout()->getBlock('shipment_tracking')->toHtml();
75  } else {
76  $response = [
77  'error' => true,
78  'message' => __('We can\'t initialize shipment for adding tracking number.'),
79  ];
80  }
81  } catch (\Magento\Framework\Exception\LocalizedException $e) {
82  $response = ['error' => true, 'message' => $e->getMessage()];
83  } catch (\Exception $e) {
84  $response = ['error' => true, 'message' => __('Cannot add tracking number.')];
85  }
86  if (is_array($response)) {
87  $response = $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($response);
88  $this->getResponse()->representJson($response);
89  } else {
90  $this->getResponse()->setBody($response);
91  }
92  }
93 }
$title
Definition: default.phtml:14
$response
Definition: 404.php:11
$track
Definition: details.phtml:12
$number
Definition: details.phtml:22
__()
Definition: __.php:13
__construct(Action\Context $context, \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader $shipmentLoader)
Definition: AddTrack.php:29
foreach($order->getItems() as $orderItem) $shipment