This article will focus on retrieving order data JSON from a controller in Magento 2. In last week’s article, we discussed creating custom routes in Magento 2. We are going to use the module created from that article as a starting point for this tutorial. You can either follow that quick process to create your custom route or download the package and use it as a starting point.
If you just want the module, download the zip file and copy it into ‘[webroot]/app/code/’. Skip to Step #5 to finish the module installation.
Download the updated HE CustomRoute Module with the JSON helper here.
Step 1: Create a Helper directory
Since the module structure is already created, it should be pretty easy to get the order data from our helper. In the examples below, we will use an interface and search criteria to get our order information.
The “Helper” folder will be stored inside the root of our module and will contain a php file. We had a default file named “Data.php” in the past. In Magento 2 we need to name these classes uniquely. It should look something like the following.
Step 2: Create OrderData.php in the Helper folder
The OrderData class will handle accessing the orderRepositoryInterface and returning data. Let’s review a couple key points. First, any external class that you want to use inside of your functions needs to be defined as a ‘use’ class. You can see that we are using ‘OrderInterface’, ‘OrderItemInterface’ and ‘SearchCriteriaBuilder’. Second, these classes need to be set as private variables. This will give us access to them in our own methods.
Now, Let’s take a look at the code:
<\?php
/**
* @package
* @version
* @author Human-Element, Inc. <[email protected]>
* @copyright Copyright 2017 Human-Element, Inc.
**/
namespace HumanElement\CustomRoute\Helper;
use Magento\Sales\Api\Data\OrderInterface;
use Magento\Sales\Api\Data\OrderItemInterface;
use Magento\Framework\Api\SearchCriteriaBuilder;
class OrderData extends \Magento\Framework\App\Helper\AbstractHelper
{
protected $_orderRepositoryInterface;
protected $_searchCriteriaBuilder;
/**
* @param \Magento\Sales\Api\OrderRepositoryInterface $orderRepository
* @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
* @param \Magento\Framework\App\Helper\Context $context
*/
public function __construct(
\Magento\Sales\Api\OrderRepositoryInterface $orderRepositoryInterface,
\Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
\Magento\Framework\App\Helper\Context $context
)
{
$this->_orderRepositoryInterface = $orderRepositoryInterface;
$this->_searchCriteriaBuilder = $searchCriteriaBuilder;
parent::__construct($context);
}
public function getOrderInfo($orderId)
{
$data = [];
$this->_searchCriteriaBuilder->addFilter('increment_id', $orderId);
$orders = $this->_orderRepositoryInterface->getList(
$this->_searchCriteriaBuilder->create()
)->getItems();
if (count($orders)) {
$order = reset($orders);
$data = $order->getData();
foreach($order->getItems() as $item) {
$data['items'][$item->getItemId()] = $item->getData();
}
}
return $data;
}
}
To learn more about the interface used in this class, check out this link.
You can get individual pieces of the order by getting the class constants provided here. The Magento devdocs do a pretty good job of describing these features as well, which you can read about here.
Step 3: Call the Helper Function from the Controller
Now that we have our helper setup and ready to use, we need to call it from the controller to retrieve the order data JSON.
Open up the file ‘app\code\HumanElement\CustomRoute\Controller\Path\Action.php’ so that we can make a couple modifications.
Add the following line into the ‘__construct’ function.
\HumanElement\CustomRoute\Helper\OrderData $orderHelper,
Then create a new private variable.
protected $_orderHelper;
Finally, replace the contents of the ‘execute’ function with our new code which will call our helper.
$oid = $this->getRequest()->getParam('oid');
$orderData = ['response'=>null];
if ($oid) {
$orderData['response'] = $this->_orderHelper->getOrderInfo($oid);
} else {
$orderData = array('error' => 'The order does not exist or was not provided');
}
$this->getResponse()->representJson($this->_jsonEncoder->encode($orderData));
return;
Step 4: Let Magento Know About the Order Data JSON Module
The only things left to do are to install the module into the database, run di:compile, and clear the cache. In this order:
cd [webroot]
php bin/magento setup:upgrade
php bin/magento setup:di:compile
php bin/magento cache:flush
Now that we have modified our module to get order data JSON, we should be able to see it on the website as well. This is the URL you should got to,
http://www.yoursite.com/humanelement/path/action?oid=[INCREMENT_ID], where you should see:
That’s it! We have successfully created a helper and expanded our controller to retrieve order data JSON information. Next week we will work on allowing custom templating.
If you have any topics that you would like us to write about, let us know!
Download the updated HE CustomRoute Module with the JSON helper here.