Skip to content

Commit a06e5bf

Browse files
authored
Merge pull request #173 from devforth/virutal-column-filter-example
docs: add filtering by virtual column example
2 parents 65225e2 + 82018f5 commit a06e5bf

File tree

1 file changed

+62
-0
lines changed

1 file changed

+62
-0
lines changed

adminforth/documentation/docs/tutorial/03-Customization/03-virtualColumns.md

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,8 @@ columns: [
6767
resource: AdminForthResourceCommon;
6868
adminUser: AdminUser
6969
}>();
70+
71+
###
7072
7173
function getFlagEmojiFromIso(iso) {
7274
return iso?.toUpperCase()?.replace(/./g, (char) => String.fromCodePoint(char.charCodeAt(0) + 127397));
@@ -78,6 +80,66 @@ Here is how it looks:
7880
7981
![alt text](<Virtual columns.png>)
8082
83+
## Virtual columns for filtering.
84+
85+
Virtual column can also be used as a shorthand for a complex filtering.
86+
Lets say we want to divide apartments into two types: "base" ones and "luxury" and then allow admins to filter apartments by this category. Condition for being a "luxury" apartment is either having more then 80 sq.m area or costing more then 100k.
87+
One way to do it is to actually add a real column to a table and then fill it every time new apartment is added. A more simple way is to add a virtual column and then use `list.beforeDatasourceRequest` hook to replace filtering on this column with desired one.
88+
For this purpose following changes will be required for apartments config:
89+
90+
```ts title='./resources/apartments.ts'
91+
...
92+
resourceId: 'aparts',
93+
...
94+
hooks: {
95+
...
96+
list: {
97+
beforeDatasourceRequest: async ({ query }: { query: any }) => {
98+
query.filters = query.filters.map((filter: any) => {
99+
// replace apartment_type filter with complex one
100+
if (filter.field === 'apartment_type') {
101+
if (filter.value === 'luxury') {
102+
return Filters.OR([Filters.GTE('square_meter', 80), Filters.GTE('price', 100000)]);
103+
}
104+
105+
// filter for "base" apartment as default
106+
return Filters.AND([Filters.LT('square_meter', 80), Filters.LT('price', 100000)]);
107+
}
108+
109+
return filter;
110+
});
111+
return { ok: true, error: "" };
112+
},
113+
...
114+
},
115+
...
116+
},
117+
...
118+
columns: [
119+
...
120+
{
121+
name: "apartment_type",
122+
virtual: true,
123+
showIn: { all: false, filter: true }, // hide it from display everywhere, except filter page
124+
enum: [
125+
{
126+
value: 'base',
127+
label: 'Base',
128+
},
129+
{
130+
value: 'luxury',
131+
label: 'Luxury'
132+
},
133+
],
134+
filterOptions: {
135+
multiselect: false, // allow to only select one category when filtering
136+
},
137+
},
138+
...
139+
]
140+
```
141+
This way, when admin selects, for example, "Luxury" option for "Apartment Type" filter, it will be replace with a more complex "or" filter.
142+
81143
82144
## Virtual columns for editing.
83145

0 commit comments

Comments
 (0)