-
Notifications
You must be signed in to change notification settings - Fork 18
Integration Fields for Magento 2
Peter Jaap Blaakmeer edited this page Nov 25, 2020
·
3 revisions
Here's a controller you could add to a custom extension and change per your liking;
<?php
/**
* Copyright © All rights reserved.
* See COPYING.txt for license details.
*/
declare(strict_types=1);
namespace Elgentos\PrismicIntegrationFields\Controller\Integration;
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
use Magento\Catalog\Ui\DataProvider\Product\ProductCollectionFactory;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Serialize\Serializer\Json;
class Products implements HttpGetActionInterface
{
/**
* @var RequestInterface
*/
public $request;
/**
* @var Json
*/
public $json;
/**
* @var JsonFactory
*/
protected $jsonFactory;
/**
* @var CollectionFactory
*/
protected $productCollectionFactory;
/**
* Constructor
*
* @param RequestInterface $request
* @param JsonFactory $jsonFactory
* @param CollectionFactory $productCollectionFactory
* @param Json $json
*/
public function __construct(
RequestInterface $request,
JsonFactory $jsonFactory,
CollectionFactory $productCollectionFactory,
Json $json
)
{
$this->productCollectionFactory = $productCollectionFactory;
$this->jsonFactory = $jsonFactory;
$this->request = $request;
$this->json = $json;
}
/**
* Execute view action
*
* @return ResultInterface
*/
public function execute()
{
$productCollection = $this->productCollectionFactory
->create()
->addAttributeToFilter('status', ['eq' => 1])
->addAttributeToSelect([ // create a select option in adminhtml/system.xml for this
'name',
'description',
'short_description',
'image',
'price',
'url_key',
])
->addAttributeToSort('updated_at', 'DESC');
$productCollection->setPageSize(50);
$productCollection->setCurPage($this->request->getParam('page'));
$results = array_values(array_map(function ($product) {
return [
'id' => $product->getId(),
'title' => $product->getName(),
'description' => $product->getShortDescription(),
'image_url' => 'https://yourdomain.com/media/catalog/product' . $product->getImage(), // Use M2 helper to get full url dynamically
'last_update' => date('U', strtotime($product->getUpdatedAt())),
'blob' => $product->getData()
];
}, $productCollection->getItems()));
$jsonResult = $this->jsonFactory->create();
$jsonResult->setData([
'results_size' => $productCollection->getSize(),
'results' => $results
]);
return $jsonResult;
}
}