With easy admin you have the possibility to sort on one field for a list.
Symfony - Easy Admin v2: Sorting Entity Listings
But is there any way to sort on more than one field for my list ?
This post will discuss how to sort a list of objects against the multiple fields in C#. 1. Using LINQ To create a sorted copy of the list, we can use LINQ’s OrderBy () method.
A Comparator can be passed to the sortWith () function to define how two items in the list should be compared. Consider the following code which creates a List<Person> and in-place sort it based on the name. If two objects have the same name, the ordering is decided by their age.
There are several ways to construct a Comparator to sort a list by multiple fields. We can pass a method reference to the compareBy, which extracts and returns a Comparator based on that function. To sort on multiple fields, we can use thenBy () to combine two comparisons. To sort in descending order, use thenByDescending () instead. 2.
1. Sorting lists of Objects on Single field/parameter : 2. Sorting list of Objects on Multiple field/parameters : Write a custom sorting logic to sort Customer member variables w.r.t 3 field/parameters as per sequence ( Name –> City –> Age) Main test class, where we are going to create ArrayList and inserts some 10+ entries of Customer objects
You can do it overriding createListQueryBuilder
or createSearchQueryBuilder
as mentioned here.
Example:
protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
/* @var EntityManager */
$em = $this->getDoctrine()->getManagerForClass($this->entity['class']);
/* @var QueryBuilder */
$queryBuilder = $em->createQueryBuilder()
->select('entity')
->from($this->entity['class'], 'entity')
;
if (!empty($dqlFilter)) {
$queryBuilder->andWhere($dqlFilter);
}
$queryBuilder->addOrderBy('entity.status', 'ASC');
$queryBuilder->addOrderBy('entity.createdAt', 'DESC');
return $queryBuilder;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With