1

I need to return array of search results and so far I did this.

DashBoardInterface.php

<?php
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
namespace Vendor\CustomAPIs\Api\Data;

/**
 * DashBoardInterface.
 * @api
 * @since 100.0.2
 */
interface DashBoardInterface
{

    const KEY_SLIDES = 'slides';
    const KEY_TOP_CATEGORIES = 'top_categories';
    const KEY_CATEGORIES = 'categories';
    const KEY_PRODUCTS = 'products';

    /**
     * Get Slides
     *
     * @return \Vendor\CustomAPIs\Api\Data\SlidesInterface[]
     */
    public function getSlides();

    /**
     * Set Slides
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria 
     * @return $this
     */
    public function setSlides($searchCriteria);

    /**
     * Get Top Categories
     *
     * @return \Magento\Catalog\Api\Data\CategorySearchResultsInterface
     */
    public function getTopCategories();

    /**
     * Set Top Categories
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return $this
     */
    public function setTopCategories($searchCriteria);

    /**
     * Get Featured Categories
     *
     * @return \Magento\Catalog\Api\Data\CategorySearchResultsInterface[]
     */
    public function getCategories();

    /**
     * Set Featured Categories
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return $this
     */
    public function setCategories($searchCriteria);

    /**
     * Get Hot Seller Products
     *
     * @return \Magento\Catalog\Api\Data\ProductSearchResultsInterface
     */
    public function getProducts();

    /**
     * Set Hot Seller Products
     *
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return $this
     */
    public function setProducts($searchCriteria);

}

DashBoardRepositoryInterface.php

<?php

namespace Vendor\CustomAPIs\Api;

/**
 * Interface DashBoardRepositoryInterface
 * @package Vendor\CustomAPIs\Api
 */
interface DashBoardRepositoryInterface
{
    const FILE_DIR = 'aw_rbslider/slides';
    const PRODUCT_LISTING = 'product_listing';
    const ACTIVE_BANNER = 'banner_tabs/general/active_banner';
    const ACTIVE_CATEGORY_SLIDER = 'banner_tabs/general/category_options';

    /**
     * Get DashBoard Data
     *
     * @return \Vendor\CustomAPIs\Api\Data\DashBoardInterface
     */
    public function getDashboardData();

}

DashBoardRepository.php

<?php

namespace Vendor\CustomAPIs\Model;

use Vendor\CustomAPIs\Api\DashBoardRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\EmailNotConfirmedException;
use Magento\Framework\Exception\InvalidEmailOrPasswordException;
use Magento\Framework\Exception\InputException;

/**
 * Class DashBoardRepository
 * @package Vendor\CustomAPIs\Model
 */
class DashBoardRepository implements DashBoardRepositoryInterface 
{
    /**
     * {@inheritdoc}
     */
    public function getDashboardData() 
    {   
        $finalData = [
           'slides' =>  $this->getFilteredSlides(),
      //     'top_categories' =>  $this->getFilteredCategories('level', 2),
           'categories' =>  $this->getFilteredCategories(),
           'products' =>  $this->getFilteredProducts('sale'),
        ];

        $dashBoardObject = $this->dashboardFactory->create();
        $this->dataObjectHelper->populateWithArray(
            $dashBoardObject,
            $finalData,
            \Vendor\CustomAPIs\Api\Data\DashBoardInterface::class
        );
        return $dashBoardObject;
    }


    private function getFilteredCategories()
    {
        $categoryTypes = $this->scopeConfig->getValue(self::ACTIVE_CATEGORY_SLIDER, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
      //  echo "<pre>";print_r(json_decode($categoryTypes));exit;
        $categories = [];
        foreach(json_decode($categoryTypes) as $categoryType) {
            $this->searchCriteriaBuilder->addFilters(
                    [
                                $this->filterBuilder
                                ->setField('is_active')
                                ->setConditionType('eq')
                                ->setValue(true)
                                ->create(),
                    ]
            );
            $this->searchCriteriaBuilder->addFilters(
                    [
                                $this->filterBuilder
                                ->setField('slider_category_type')
                                ->setConditionType('eq')
                                ->setValue($categoryType->option_value)
                                ->create(),
                    ]
            );

            $searchCriteria = $this->searchCriteriaBuilder->create();
            $categories[$categoryType->option_value] = $this->categoryList->getList($searchCriteria);
        }

//        foreach ($searchResult->getItems() as $item)
//        {
//            echo "<pre>";print_r($item->getTotalCount());
//        }
//        exit;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $objectManager->create('Psr\Log\LoggerInterface')->debug('data', [$categories]);
        return $categories;
    }

}

Now issue in that code is when I return categories from getFilteredCategories() it returns array of object and it throws error that populateWithArray function expect parameter 2 be array object given. I know it is due to I defined array of CategorySearchResultsInterface[] in DashBoardInterface. Basically I want that categories should return like.

slides :{}
---
---
categories : {
   featured_categories : {
     items : [
        {},
        {}
     ]
   },
   new_categories : {
     items : [
        {},
        {}
     ]
   }
}

And same will be for products. Please help if anyone have done this before.

1

I just fixed this. Need to create one more interface for this.

CategoryArrayItemInterface

<?php
namespace Vendor\CustomAPIs\Api\Data;

/**
 * Interface which represents associative array item.
 */
interface CategoryArrayItemInterface
{
    const KEY = "key";
    const KEY_VALUE = "value";

    /**
     * Get key
     * 
     * @return string
     */
    public function getKey();

    /**
     * Set key
     * 
     * @return string
     */
    public function setKey($key);

    /**
     * Get value
     * 
     * @return \Magento\Catalog\Api\Data\CategorySearchResultsInterface
     */
    public function getValue();

    /**
     * Set value
     * 
     * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
     * @return $this
     */
    public function setValue($searchCriteria);
}

and use this interface in my DashBoardInterface like below.

/**
 * Get Categories
 *
 * @return \Vendor\Module\Api\Data\CategoryArrayItemInterface[]
 */
public function getCategories();

/**
 * Set Categories
 *
 * @param \Magento\Framework\Api\SearchCriteriaInterface $searchCriteria
 * @return $this
 */
public function setCategories($searchCriteria);

and update getFilteredCategories() function like below.

private function getFilteredCategories()
{
    $categoryTypes = $this->scopeConfig->getValue(self::ACTIVE_CATEGORY_SLIDER, \Magento\Store\Model\ScopeInterface::SCOPE_STORE);
    $categories = [];
    foreach(explode(',', $categoryTypes) as $categoryType) {
        $this->searchCriteriaBuilder->addFilters(
                [
                            $this->filterBuilder
                            ->setField('is_active')
                            ->setConditionType('eq')
                            ->setValue(true)
                            ->create(),
                ]
        );
        $this->searchCriteriaBuilder->addFilters(
                [
                            $this->filterBuilder
                            ->setField('slider_category_type')
                            ->setConditionType('eq')
                            ->setValue($categoryType)
                            ->create(),
                ]
        );

        $searchCriteria = $this->searchCriteriaBuilder->create();
        $categories[] = [
            'key' => $categoryType,
            'value' => $this->categoryList->getList($searchCriteria)
        ];
    }

    return $categories;
}

Thanks to @Alex Paliarush for this exmaple. Let me know if anyone needs more explanation on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.