Magento2 | PWA | GraphQL

Add Sort Order with sortOrderBuilder in Magento2


To add Sort order in Magento,
Add \Magento\Framework\Api\SortOrderBuilder $sortOrderBuilder as dependency in constructor.

Base Definition Class:

\Magento\Framework\Api\SortOrderBuilder

In this Base class you can find below methods for sorting:

  • setField
  • setDirection
  • setAscendingDirection
  • setDescendingDirection

Check the below code snippet:
public function getSlides(int $sliderId, bool $onlyEnabled = false, bool $sorted = false): array
{
    $this->searchCriteriaBuilder->addFilter(SlideInterface::SLIDER_ID, $sliderId);

    if ($sorted) {
        $sortOrder = $this->sortOrderBuilder->setField(SlideInterface::POSITION)
        ->setAscendingDirection()->create();
        $this->searchCriteriaBuilder->addSortOrder($sortOrder);
    }

    $searchCriteria = $this->searchCriteriaBuilder->create();
    $slides         = $this->slideRepository->getList($searchCriteria);

    return $slides->getItems();
}

Now from above code snippet:

1. $this->sortOrderBuilder:

  • This is an instance of a class that helps in building sort orders. In Magento 2, this is often an instance of Magento\Framework\Api\SortOrderBuilder.
2. setField():
  • This method sets the field by which the collection should be sorted. For example, if you want to sort by name, you would call setField('name').
3. setAscendingDirection():
  • This method specifies the direction of the sort. It typically sorts in ascending order. There’s also usually a setDescendingDirection() method if you want to sort in descending order.
4. create():
  • This method finalizes and creates the sort order object based on the provided field and direction.

Example in Context

Here’s a more detailed example showing how you might use these methods:

// Create a sort order builder instance
$sortOrderBuilder = $this->sortOrderBuilder;

// Set the field to sort by
$sortOrderBuilder->setField('name');

// Set the sort direction to ascending
$sortOrderBuilder->setAscendingDirection();

// Create the sort order object
$sortOrder = $sortOrderBuilder->create();

In this example, we are creating a sort order that will sort by the name field in ascending order.

Usage

The created SortOrder object can then be used to modify the collection’s sorting:
$collection->setOrder('name', 'ASC');

Tag : Magento2
0 Comments On "Add Sort Order with sortOrderBuilder in Magento2"

Back To Top