Search code examples
phptypo3typo3-7.6.xtypo3-8.xtypo3-extensions

How to set sorting in default repository function in Typo3?


I have written like this

/**
 * itemRepository
 *
 * @var \KRT\KrtEmployee\Domain\Repository\ItemRepository
 * @inject
 */
 protected $itemRepository = null;

/**
 * action list
 *
 * @return void
 */
public function listAction()
{
    $arguments =$this->request->getArguments();     

    $employees = $this->itemRepository->findAll();        
    $this->view->assign('employees',$employees);
}

In my $employees result I have

  • Employee ID (Default uid)
  • Name
  • Designation
  • Department
  • Salary

Now, How can I Sort the result array in ascending order based on

  1. Name
  2. Department and Salary

Is there any default function to sort inside the repository queries?


Solution

  • Every repository has a $defaultOrderings property where you can specify the default orderings applied to all query methods. In your case it could look like this:

    protected $defaultOrderings = [
        'name' => QueryInterface::ORDER_ASCENDING,
        'department.name' => QueryInterface::ORDER_ASCENDING,
        'salary' => QueryInterface::ORDER_ASCENDING,
    ];
    

    As you can see with department.name you can also sort by properties of relations. Notice that this only works for 1:1 and n:1 relations.

    In case of custom query methods in your repository you can manually set the orderings directly on the query:

    $query->setOrderings([
        'name' => QueryInterface::ORDER_ASCENDING,
        'department.name' => QueryInterface::ORDER_ASCENDING,
        'salary' => QueryInterface::ORDER_ASCENDING,
    ]);