@@ -5,6 +5,8 @@ API Platform Core provides an easy way to override the default order of items in
5
5
By default, items in the collection are ordered in ascending (ASC) order by their resource identifier(s). If you want to
6
6
customize this order, you must add an ` order ` attribute on your ApiResource annotation:
7
7
8
+ [ codeSelector]
9
+
8
10
``` php
9
11
<?php
10
12
// api/src/Entity/Book.php
@@ -28,9 +30,20 @@ class Book
28
30
}
29
31
```
30
32
33
+ ``` yaml
34
+ # config/api/resources/Book.yaml
35
+ App\Entity\Book :
36
+ attributes :
37
+ order : { foo: ASC }
38
+ ` ` `
39
+
40
+ [/codeSelector]
41
+
31
42
This ` order` attribute is used as an array: the key defines the order field, the values defines the direction.
32
43
If you only specify the key, `ASC` direction will be used as default. For example, to order by `foo` & `bar` :
33
44
45
+ [codeSelector]
46
+
34
47
` ` ` php
35
48
<?php
36
49
// api/src/Entity/Book.php
@@ -59,8 +72,19 @@ class Book
59
72
}
60
73
` ` `
61
74
75
+ ` ` ` yaml
76
+ # config/api/resources/Book.yaml
77
+ App\E ntity\B ook:
78
+ attributes:
79
+ order: ['foo', 'bar']
80
+ ` ` `
81
+
82
+ [/codeSelector]
83
+
62
84
It's also possible to configure the default order on an association property :
63
85
86
+ [codeSelector]
87
+
64
88
` ` ` php
65
89
<?php
66
90
// api/src/Entity/Book.php
@@ -84,8 +108,19 @@ class Book
84
108
}
85
109
` ` `
86
110
111
+ ` ` ` yaml
112
+ # config/api/resources/Book.yaml
113
+ App\E ntity\B ook:
114
+ attributes:
115
+ order: ['author.username']
116
+ ` ` `
117
+
118
+ [/codeSelector]
119
+
87
120
Another possibility is to apply the default order for a specific collection operation, which will override the global default order configuration.
88
121
122
+ [codeSelector]
123
+
89
124
` ` ` php
90
125
/**
91
126
* collectionOperations={
@@ -106,3 +141,19 @@ class Book
106
141
// ...
107
142
}
108
143
` ` `
144
+
145
+ ` ` ` yaml
146
+ # config/api/resources/Book.yaml
147
+ App\E ntity\B ook:
148
+ get: ~
149
+ get_desc_custom:
150
+ method: get
151
+ path: custom_collection_desc_foos
152
+ order: {name: DESC}
153
+ get_asc_custom:
154
+ method: get
155
+ path: custom_collection_asc_foos
156
+ order: {name: ASC}
157
+ ` ` `
158
+
159
+ [/codeSelector]
0 commit comments