0

I have created a repository to retrieve records from database. I need to sort the records using a specific column. I tried to use the SortOrderBuilder but it returns Fatal error: Class 'Qooar\CustomerMessage\Model\ResourceModel\SortOrder' not found. Below is my function in the block and my repository class.

The getList function in the block

public function getList() {

        $filterGroups = [
            $this->filterGroupBuilder->setFilters(
                    [
                        $this->filterBuilder->setField('customer_id')->setConditionType('eq')->setValue(1)->create(),
                    ]
            )->create(),
            $this->filterGroupBuilder->setFilters(
                    [
                        $this->filterBuilder->setField('created_at')->setConditionType('gteq')->setValue("2016-09-01")->create(),
                    ]
            )->create(),
            $this->filterGroupBuilder->setFilters(
                    [
                        $this->filterBuilder->setField('created_at')->setConditionType('lteq')->setValue("2016-09-30")->create(),
                    ]
            )->create(),
        ];
        $this->searchCriteriaBuilder->setFilterGroups($filterGroups);

        // To fix: Fatal error: Class 'Qooar\CustomerMessage\Model\ResourceModel\SortOrder' not found
        $sortOrders = [
            $this->sortOrderBuilder->setField('customer_id')->setDirection(\Magento\Framework\Api\SortOrder::SORT_DESC)->create()
        ];
        $this->searchCriteriaBuilder->setSortOrders($sortOrders);

        $searchResults = $this->customerMessageRepository->getList($this->searchCriteriaBuilder->create());

        return $searchResults->getItems();
    }

Repository Class

<?php

namespace Qooar\CustomerMessage\Model\ResourceModel;

use Magento\Framework\Api\SearchCriteriaInterface;
use \Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Exception\InputException;

/**
 * Customer message repository.
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class CustomerMessageRepository implements \Qooar\CustomerMessage\Api\CustomerMessageRepositoryInterface {

    protected $customerMessageFactory;
    protected $searchResultsFactory;
    protected $logger;

    public function __construct(\Qooar\CustomerMessage\Model\CustomerMessageFactory $customerMessageFactory, //
            \Qooar\CustomerMessage\Api\Data\CustomerMessageSearchResultsInterfaceFactory $searchResultsFactory, //
            \Psr\Log\LoggerInterface $logger //
    ) {
        $this->customerMessageFactory = $customerMessageFactory;
        $this->searchResultsFactory = $searchResultsFactory;
        $this->logger = $logger;
    }

    public function delete(\Qooar\CustomerMessage\Api\Data\CustomerMessageInterface $customerMessage) {
        return $this->deleteById($customerMessage->getId());
    }

    public function deleteById($customerMessageId) {
        $customerMessage = $this->getById($customerMessageId);
        $customerMessage->delete();
        return true;
    }

    public function getById($customerMessageId) {

        $customerMessage = $this->customerMessageFactory->create()->load($customerMessageId);

        if (!$customerMessage->getId()) {
            // does not exist
            throw NoSuchEntityException::singleField('id', $customerMessageId);
        } else {
            return $customerMessage;
        }
    }

    public function getList(SearchCriteriaInterface $searchCriteria) {

        // search
        $collection = $this->customerMessageFactory->create()->getCollection();
        foreach ($searchCriteria->getFilterGroups() as $group) {
            $this->addFilterGroupToCollection($group, $collection);
        }

        // sort
        $sortOrders = $searchCriteria->getSortOrders();
        if ($sortOrders) {
            foreach ($searchCriteria->getSortOrders() as $sortOrder) {
                $collection->addOrder(
                        $sortOrder->getField(), ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
                );
            }
        }

        // join table
        $collection->getSelect()->joinLeft(array('ce' => 'customer_entity'), 'ce.entity_id = main_table.customer_id', array('customer_entity_email' => 'email'));

        // limit
        $collection->setCurPage($searchCriteria->getCurrentPage());
        $collection->setPageSize($searchCriteria->getPageSize());

        // sql
        $this->logger->debug("SQL: {$collection->getSelectSql(true)}");

        // result
        $searchResults = $this->searchResultsFactory->create();
        $searchResults->setSearchCriteria($searchCriteria);
        $searchResults->setTotalCount($collection->getSize());

        $customerMessages = [];
        foreach ($collection as $customerMessage) {
            $customerMessages[] = $customerMessage;
        }
        $searchResults->setItems($customerMessages);

        return $searchResults;
    }

    public function save(\Qooar\CustomerMessage\Api\Data\CustomerMessageInterface $customerMessage) {
        $this->validate($customerMessage);
        $customerMessage->save();
    }

    protected function addFilterGroupToCollection(\Magento\Framework\Api\Search\FilterGroup $filterGroup, \Qooar\CustomerMessage\Model\ResourceModel\CustomerMessage\Collection $collection
    ) {
        $fields = [];
        $conditions = [];

        foreach ($filterGroup->getFilters() as $filter) {
            $fields[] = 'main_table.' . $filter->getField();
            $conditions[] = [$filter->getConditionType() => $filter->getValue()];
        }
        if ($fields) {
            $collection->addFieldToFilter($fields, $conditions);
        }
    }

    protected function validate(\Qooar\CustomerMessage\Api\Data\CustomerMessageInterface $customerMessage) {
        $exception = new InputException();
        if (!\Zend_Validate::is($customerMessage->getCustomerId(), 'NotEmpty')) {
            $exception->addError(__(InputException::REQUIRED_FIELD, ['fieldName' => 'customer_id']));
        }

        if ($exception->wasErrorAdded()) {
            throw $exception;
        }
    }

}

The full source is at github.

  • Refer to vendor\magento\framework\Api\Test\Unit\SortOrderTest.php u will get Idea when u wrong – Ankit Shah Sep 23 '16 at 3:09
  • I have checked the SortOrderBuilder class and also the SortOrderTest but still no glue. – Paul Sep 25 '16 at 23:58

Your Answer

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

Browse other questions tagged or ask your own question.