Quantcast
Channel: Yudiz Solutions Ltd.
Viewing all articles
Browse latest Browse all 595

Magento 2 – Multi Site product filter using REST API

$
0
0

The first question that arise on looking at the tile is: What is Multi Site to do with REST API?

The answer is simple, Magento provides multi-site support and mobile application needs the same support through REST API.

The following steps will allow a developer to develop a module which will provide product filters for multiple sites with the help of RETS API.

Step 1:

Create a custom module Company Name/ Module Name like: Demo/Simple – I am pretty sure you can make this.

Step 2:

Create file ProductListInterface.php in Demo/Simple/Api Folder

Step 3:

Place the below code in ProductListInterface.php

<?php
    namespace Demo\Simple\Api;

    interface ProductListInterface
    {
        /**
        * Get product list
        *
        * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
        * @param string $websiteIds
        * @return \Magento\Catalog\Api\Data\ProductSearchResultsInterface
        */
        public function getProductList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria,$websiteIds);
    }

This will allow the different search criteria filter.

Step 4:

Then create di.xml in Demo/Simple/etc Folder

Step 5:

Place the below code in di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
  <preference for="Demo\Simple\Api\ProductListInterface" type="Demo\Simple\Model\ProductList" />
</config>

This will create a dependency to model.

Step 6:

Then create webapi.xml in Demo/Simple/etc Folder

Step 7:

Place the below code in webapi.xml

<?xml version="1.0"?>
<!--
/**
* Copyright 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<routes xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../app/code/Magento/Webapi/etc/webapi.xsd">

<!-- Product List -->
<route url="/V1/productList" method="GET">
    <service class="Demo\Simple\Api\ProductListInterface" method="getProductList"/>
    <resources>
        <resource ref="anonymous"/>
    </resources>
</route>

</routes>

This will create routing for method.

Step 8:

Then create file ProductList.php in Demo/Simple/Model Folder

Step 9:

Place below code in ProductList.php

<?php

namespace Demo\Simple\Model;

use Demo\Simple\Api\ProductListInterface;

/**
* Defines the implementaiton class of the calculator service contract.
*/
class ProductList implements ProductListInterface
{
    protected $_objectManager = null;
      protected $_tokenkFactory;

      /**
      * @var \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory
    */
      protected $collectionFactory;

      /**
    * @var \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface
    */
    protected $extensionAttributesJoinProcessor;

    /**
    * @var \Magento\Catalog\Api\ProductAttributeRepositoryInterface
    */
    protected $metadataService;

    /**
    * @var \Magento\Framework\Api\SearchCriteriaBuilder
    */
  protected $searchCriteriaBuilder;

  /**
    * @var \Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory
    */
  protected $searchResultsFactory;
   
      public function __construct(
       \Demo\Simple\Model\WsOauthTokenFactory $_tokenkFactory,
       \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $collectionFactory,
       \Magento\Catalog\Model\ResourceModel\Product $resourceModel,
       \Magento\Framework\ObjectManagerInterface $objectManager,
       \Magento\Store\Model\StoreManagerInterface $storeManager,
       \Magento\Framework\Api\ExtensionAttribute\JoinProcessorInterface $extensionAttributesJoinProcessor,
       \Magento\Catalog\Api\ProductAttributeRepositoryInterface $metadataServiceInterface,
       \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder,
       \Magento\Catalog\Api\Data\ProductSearchResultsInterfaceFactory $searchResultsFactory,
       \Magento\CatalogInventory\Model\StockRegistry $stock
    )
      {
          $this->_objectManager = $objectManager;
          $this->_tokenkFactory = $_tokenkFactory;
          $this->_storeManager = $storeManager;
          $this->collectionFactory = $collectionFactory;
          $this->extensionAttributesJoinProcessor = $extensionAttributesJoinProcessor;
          $this->metadataService = $metadataServiceInterface;
          $this->searchCriteriaBuilder = $searchCriteriaBuilder;
          $this->searchResultsFactory = $searchResultsFactory;
          $this->resourceModel = $resourceModel;
          $this->stockRegistryProvider = $stock;
      }


   public function getProductList(\Magento\Framework\Api\SearchCriteriaInterface $searchCriteria,$websiteIds)
  {

     $webSites = explode(',', $websiteIds);

      /** @var \Magento\Catalog\Model\ResourceModel\Product\Collection $collection */
      $collection = $this->collectionFactory->create();
      $this->extensionAttributesJoinProcessor->process($collection);

      foreach ($this->metadataService->getList($this->searchCriteriaBuilder->create())->getItems() as $metadata) {
          $collection->addAttributeToSelect($metadata->getAttributeCode());
      }
      $collection->joinAttribute('status', 'catalog_product/status', 'entity_id', null, 'inner');
      $collection->joinAttribute('visibility', 'catalog_product/visibility', 'entity_id', null, 'inner');      
      $collection->addWebsiteFilter($webSites);

      // filter for out of stock product
    $cond = array(
      '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=1 AND {{table}}.is_in_stock=1',
      '{{table}}.use_config_manage_stock = 0 AND {{table}}.manage_stock=0',
     );


     $cond[] = '{{table}}.use_config_manage_stock = 1 AND {{table}}.is_in_stock=1';
       
      $collection->joinField(
          'inventory_in_stock',
          'cataloginventory_stock_item',
          'is_in_stock',
          'product_id=entity_id',
          '(' . join(') OR (', $cond) . ')'
      );

      //Add filters from root filter group to the collection
      foreach ($searchCriteria->getFilterGroups() as $group) {
          $this->addFilterGroupToCollection($group, $collection);
      }
      /** @var SortOrder $sortOrder */
      foreach ((array)$searchCriteria->getSortOrders() as $sortOrder) {
          $field = $sortOrder->getField();
          $collection->addOrder(
              $field,
              ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
          );
      }
      $collection->setCurPage($searchCriteria->getCurrentPage());
      $collection->setPageSize($searchCriteria->getPageSize());
      $collection->load();

      $searchResult = $this->searchResultsFactory->create();
      $searchResult->setSearchCriteria($searchCriteria);
      $searchResult->setItems($collection->getItems());
      $searchResult->setTotalCount($collection->getSize());
      return $searchResult;
  }

  /**
    * Helper function that adds a FilterGroup to the collection.
    *
    * @param \Magento\Framework\Api\Search\FilterGroup $filterGroup
    * @param Collection $collection
    * @return void
    */
  protected function addFilterGroupToCollection(
      \Magento\Framework\Api\Search\FilterGroup $filterGroup,
      Collection $collection
  ) {
      $fields = [];
      $categoryFilter = [];
      foreach ($filterGroup->getFilters() as $filter) {
          $conditionType = $filter->getConditionType() ? $filter->getConditionType() : 'eq';

          if ($filter->getField() == 'category_id') {
              $categoryFilter[$conditionType][] = $filter->getValue();
              continue;
          }
          $fields[] = ['attribute' => $filter->getField(), $conditionType => $filter->getValue()];
      }

      if ($categoryFilter) {
          $collection->addCategoriesFilter($categoryFilter);
      }

      if ($fields) {
          $collection->addFieldToFilter($fields);
      }
  }
}

Step 10:

Run this REST API thru URL
http://yourdomain.com/rest/V1/productList?searchCriteria[current_page]=1&searchCriteria[page_size]=10&websiteIds=1

All Done.

Here are list of filter parameters which can be used via this:

searchCriteria[filter_groups][0][filters][0][field]=sku&
searchCriteria[filter_groups][0][filters][0][value]=simple&
searchCriteria[filter_groups][0][filters][0][condition_type]=eq&
searchCriteria[current_page]=1&
searchCriteria[page_size]=10&
websiteIds=1,2


Viewing all articles
Browse latest Browse all 595

Trending Articles