Create and manage Smart Views

What is a Smart View?

This feature requires a Starter plan or higher. However, it's free to try in non-production environments.
Smart Views lets you code your view using JS, HTML, and CSS. They are taking data visualization to the next level. Ditch the table view and display your orders on a Map, your events in a Calendar, your movies, pictures and profiles in a Gallery. All of that with the easiness of Forest Admin.

Creating a Smart View

Forest Admin provides an online editor to inject your Smart View code. The editor is available on the collection’s settings, then in the “Smart views” tab.
The code of a Smart View is an Ember Component and simply consists of a Template and Javascript code.
You don’t need to know the Ember.js framework to create a Smart View. We will guide you here on all the basic requirements. For more advanced usage, you can still refer to the Ember Component and the Handlebars Template documentations.

Getting your records

The records of your collection are accessible from the records property. Here’s how to iterate over them in the template section:
1
{{#each @records as |record|}}
2
{{/each}}
Copied!

Accessing a specific record

For each record, you will access its attributes through the forest-attribute property. The forest- preceding the field name is required.
1
{{#each @records as |record|}}
2
<p>status: {{record.forest-shipping_status}}</p>
3
{{/each}}
Copied!

Accessing belongsTo relationships

Accessing a belongsTo relationship works in exactly the same way as accessing a simple field. Forest triggers automatically an API call to retrieve the data from your Admin API only if it’s necessary.
On the Shipping Smart View (in the collection named Order) defined on our Live Demo example, we’ve displayed the full name of the customer related to an order.
1
{{#each @records as |record|}}
2
<h2>Order to {{record.forest-customer.forest-firstname}} {{record.forest-customer.forest-lastname}}</h2>
3
{{/each}}
Copied!

Accessing hasMany relationships

Accessing a hasMany relationship works in exactly the same way as accessing a simple field.. Forest triggers automatically an API call to retrieve the data from your Admin API only if it’s necessary.
1
{{#each @records as |record|}}
2
{{#each @record.forest-comments as |comment|}}
3
<p>{{comment.forest-text}}</p>
4
{{/each}}
5
{{/each}}
Copied!

Refreshing data

Trigger the fetchRecords action in order to refresh the records on the page.
1
<button {{on 'click' @fetchRecords}}>
2
Refresh data
3
</button>
Copied!

Fetching data

Trigger an API call to your Admin API in order to fetch records from any collection and with any filters you want.
We will use the store service for that purpose. Check out the list of all available services from your Smart View.
In our Live Demo example, the collection appointments has a Calendar Smart View. When you click on the previous or next month, the Smart View fetches the new events in the selected month. The result here is set to the propertyappointments. You can access it directly from your template.
component.js
1
import Component from '@glimmer/component';
2
import { inject as service } from '@ember/service';
3
import { tracked } from '@glimmer/tracking';
4
5
export default class extends Component {
6
@service store;
7
8
@tracked appointments;
9
10
async fetchData(startDate, endDate) {
11
const params = {
12
filters: JSON.stringify({
13
aggregator: 'and',
14
conditions: [{
15
field: 'start_date',
16
operator: 'greater_than'
17
value: startDate,
18
}, {
19
field: 'start_date',
20
operator: 'less_than'
21
value: endDate,
22
}],
23
}),
24
timezone: 'America/Los_Angeles',
25
'page[number]': 1,
26
'page[size]': 50
27
};
28
29
this.appointments = await this.store.query('forest_appointment', params);
30
}
31
// ...
32
};
Copied!
template.hbs
1
{{#each this.appointments as |appointment|}}
2
<p>{{appointment.id}}</p>
3
<p>{{appointment.forest-name}}</p>
4
{{/each}}
Copied!

Available parameters

Parameter
Type
Description
filters
Object
A stringified JSON object containing either:
    a filter
    an aggregation of several filters
A filter is built using the following template:
{
field: <a field name>
operator: <an operator name>
value: <a value>
}
An aggregation is built using the following template
{
aggregator: <and or or>
conditions: <an array of filters or aggregations>
}
List of available operators is: less_than, greater_than, equal, after, before, contains, starts_with, ends_with, not_contains, present, not_equal, blank
timezone
String
The timezone string. Example: America/Los_Angeles.
page[number]
Number
The page number you want to fetch.
page[size]
Number
The number of records per page you want to fetch.

Deleting records

The deleteRecords action lets you delete one or multiple records. A pop-up will automatically ask for a confirmation when a user triggers the delete action.
template.hbs
1
{{#each @records as |record|}}
2
<Button::BetaButton
3
@type="danger"
4
@text="Delete record"
5
@action={{fn this.deleteRecords record}}
6
@async={{false}}
7
/>
8
{{/each}}
Copied!

Triggering a Smart Action

Please note that the smart action triggering in the context of the smart view editor can be broken as you might not have access to all the required information. We advise you to test the smart action execution from the smart view applied to the collection view.
Here’s how to trigger your Smart Actions directly from your Smart Views.
template.hbs
component.js
1
<Button::BetaButton
2
@type="primary"
3
@text="Reschedule appointment"
4
@action={{fn this.triggerSmartAction @collection 'Reschedule' record}}
5
/>
Copied!
1
import Component from '@glimmer/component';
2
import { action } from '@ember/object';
3
import { triggerSmartAction } from 'client/utils/smart-view-utils';
4
5
export default class extends Component {
6
@action
7
triggerSmartAction(...args) {
8
return triggerSmartAction(this, ...args);
9
}
10
11
@action
12
deleteRecords(...args) {
13
return deleteRecords(this, ...args);
14
}
15
}
Copied!
triggerSmartAction function imported from 'client/utils/smart-view-utils'has the following signature:
1
function triggerSmartAction(
2
context, collection, actionName, records, callback = () => {}, values = null,
3
)
Copied!
Argument name
Description
context
Context is the reference to the component, in the smart view it is accessible through the keyword this
collection
The collection that has the Smart Action
actionName
The Smart Action name
records
An array of records or a single one
callback
A function executed after the smart action that takes as the single parameter the result of the smart action execution.
values
An object containing the values to be passed for the smart action fields
Here is an example of how to trigger the smart action with the values passed from the code, you only need to do it if you don't want to use the built-in smart action form
template.hbs
component.js
1
<Button::BetaButton
2
@type="primary"
3
@text="Reschedule appointment"
4
@action={{fn this.rescheduleToNewTime record}}
5
/>
Copied!
1
import Component from '@glimmer/component';
2
import { action } from '@ember/object';
3
import { triggerSmartAction } from 'client/utils/smart-view-utils';
4
import { tracked } from '@glimmer/tracking'
5
6
export default class extends Component {
7
8
@tracked newTime = '11:00';
9
10
@action
11
triggerSmartAction(actionName, records, values) {
12
return triggerSmartAction(
13
this,
14
this.args.collection,
15
actionName,
16
records,
17
() => {},
18
values,
19
);
20
}
21
22
@action
23
rescheduleToNewTime(record) {
24
this.triggerSmartAction('Reschedule', record, { newTime })
25
}
26
27
@action
28
deleteRecords(...args) {
29
return deleteRecords(this, ...args);
30
}
31
}
Copied!

Available properties

Forest Admin automatically injects into your Smart View some properties to help you display your data like you want.
Property
Type
Description
collection
Model
The current collection.
currentPage
Number
The current page.
isLoading
Boolean
Indicates if the UI is currently loading your records.
numberOfPages
Number
The total number of available pages
records
array
Your data entries.
searchValue
String
The current search.

Available actions

Forest Admin automatically injects into your Smart View some actions to trigger the logic you want.
Action
Description
deleteRecords(records)
Delete one or multiple records.
triggerSmartAction(collection, actionName, record)
Trigger a Smart Action defined on the specified collection on a record.

Examples

On our Live Demo, we have 4 Smart Views defined:

Example: Map view

component.js
1
import Component from '@glimmer/component';
2
import { inject as service } from '@ember/service';
3
import { scheduleOnce } from '@ember/runloop';
4
import { action } from '@ember/object';
5
import { observes } from '@ember-decorators/object';
6
import { tracked } from '@glimmer/tracking';
7
import { guidFor } from '@ember/object/internals';
8
import { triggerSmartAction, deleteRecords, getCollectionId, loadExternalStyle, loadExternalJavascript } from 'client/utils/smart-view-utils';
9
10
export default class extends Component {
11
@service router;
12
@service store;
13
14
@tracked map = null;
15
@tracked loaded = false;
16
17
constructor(...args) {
18
super(...args);
19
20
this.loadPlugin();
21
}
22
23
@observes('records.[]')
24
onRecordsChange() {
25
this.displayMap();
26
}
27
28
get mapId() {
29
return `map-${guidFor(this)}`;
30
}
31
32
async loadPlugin() {
33
loadExternalStyle('//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.css');
34
loadExternalStyle('//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.css');
35
36
await loadExternalJavascript('//cdnjs.cloudflare.com/ajax/libs/leaflet/1.3.1/leaflet.js');
37
await loadExternalJavascript('//cdnjs.cloudflare.com/ajax/libs/leaflet.draw/1.0.2/leaflet.draw.js');
38
39
this.loaded = true;
40
this.displayMap();
41
}
42
43
@action
44
displayMap() {
45
if (!this.loaded) { return; }
46
47
if (this.map) {
48
this.map.off();
49
this.map.remove();
50
this.map = null;
51
}
52
53
const markers = [];
54
55
this.args.records.forEach(function (record) {
56
markers.push([
57
record.get('forest-lat'),
58
record.get('forest-lng'),
59
record.get('id'),
60
]);
61
});
62
63
this.map = new L.Map(this.mapId);
64
65
const osmUrl = 'https://cartodb-basemaps-{s}.global.ssl.fastly.net/light_all/{z}/{x}/{y}.png';
66
const osmAttrib = '&copy; <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a> &copy; <a href="http://cartodb.com/attributions">CartoDB</a>';
67
const osm = new L.TileLayer(osmUrl, { attribution: osmAttrib });
68
const drawnItems = new L.FeatureGroup();
69
this.map.addLayer(drawnItems);
70
71
const drawControl = new L.Control.Draw({
72
draw: {
73
polygon: false,
74
polyline: false,
75
rectangle: false,
76
circle: false,
77
circlemarker: false,
78
marker: true
79
},
80
edit: {
81
featureGroup: drawnItems
82
},
83
});
84
85
this.map.setView(new L.LatLng(48.8566, 2.3522), 2);
86
this.map.addLayer(osm);
87
this.map.addControl(drawControl);
88
89
this.map.on(L.Draw.Event.CREATED, (event) => {
90
const { layer, layerType: type } = event;
91
92
if (type === 'marker') {
93
const coordinates = event.layer.getLatLng();
94
const newRecord = this.store.createRecord('forest_delivery', {
95
'forest-is_delivered': false,
96
'forest-lng': coordinates.lng,
97
'forest-lat': coordinates.lat
98
});
99
100
newRecord.save()
101
.then((savedRecord) => {
102
layer.on('click', () => {
103
this.router.transitionTo(
104
'project.rendering.data.collection.list.viewEdit.details',
105
this.args.collection.id,
106
savedRecord.id,
107
);
108
});
109
});
110
}
111
112
this.map.addLayer(layer);
113
});
114
115
this.addMarkers(markers);
116
}
117
118
addMarker(marker) {
119
const lat = Number.parseFloat(marker[0]);
120
const long = Number.parseFloat(marker[1]);
121
122
const recordId = marker[2];
123
marker = L.marker([lat, long])
124
.addTo(this.map);
125
126
marker.on('click', () => {
127
this.router.transitionTo(
128
'project.rendering.data.collection.list.viewEdit.details',
129
this.args.collection.id,
130
recordId,
131
);
132
});
133
}
134
135
addMarkers(markers) {
136
markers.forEach(marker => this.addMarker(marker));
137
}
138
139
@action
140
triggerSmartAction(...args) {
141
return triggerSmartAction(this, ...args);
142
}
143
144
@action
145
deleteRecords(...args) {
146
return deleteRecords(this, ...args);
147
}
148
}
Copied!
template.hbs
1
<style>
2
.c-map {
3
width: 100%;
4
height: 100%;
5
z-index: 4;
6
}
7
</style>
8
9
<div id={{this.mapId}} class="c-map" {{did-insert this.displayMap}}></div>
Copied!

Example: Calendar view

1
import Component from '@glimmer/component';
2
import { inject as service } from '@ember/service';
3
import { scheduleOnce } from '@ember/runloop';
4
import { action } from '@ember/object';
5
import { observes } from '@ember-decorators/object';
6
import { tracked } from '@glimmer/tracking';
7
import { guidFor } from '@ember/object/internals';
8
import $ from 'jquery';
9
import { triggerSmartAction, deleteRecords, getCollectionId, loadExternalStyle, loadExternalJavascript } from 'client/utils/smart-view-utils';
10
11
export default class extends Component {
12
@service() router;
13
@service() store;
14
15
@tracked conditionAfter = null;
16
@tracked conditionBefore = null;
17
@tracked loaded = false;
18
19
constructor(...args) {
20
super(...args);
21
22
this.loadPlugin();
23
}
24
25
@observes('records.[]')
26
onRecordsChange() {
27
this.setEvent();
28
}
29
30
get calendarId() {
31
return `${guidFor(this)}-calendar`;
32
}
33
34
async loadPlugin() {
35
loadExternalStyle('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.css');
36
await loadExternalJavascript('//cdnjs.cloudflare.com/ajax/libs/fullcalendar/3.1.0/fullcalendar.min.js');
37
this.loaded = true;
38
}
39
40
@action
41
onInsert() {
42
$(`#${this.calendarId}`).fullCalendar({
43
allDaySlot: false,
44
minTime: '00:00:00',
45
defaultDate: new Date(2018, 2, 1),
46
eventClick: (event, jsEvent, view) => {
47
this.router.transitionTo(
48
'project.rendering.data.collection.list.viewEdit.details',
49
this.args.collection.id,
50
event.id,
51
);
52
},
53
viewRender: (view) => {
54
const field = this.args.collection.fields.findBy('field', 'start_date');
55
56
if (this.conditionAfter) {
57
this.removeCondition(this.conditionAfter, true);
58
this.conditionAfter.destroyRecord();
59
}
60
if (this.conditionBefore) {
61
this.removeCondition(this.conditionBefore, true);
62
this.conditionBefore.destroyRecord();
63
}
64
65
const conditionAfter = this.store.createRecord('condition');
66
conditionAfter.set('field', field);
67
conditionAfter.set('operator', 'is after');
68
conditionAfter.set('value', view.start);
69
conditionAfter.set('smartView', this.args.viewList);
70
this.set('conditionAfter', conditionAfter);
71
72
const conditionBefore = this.store.createRecord('condition');
73
conditionBefore.set('field', field);
74
conditionBefore.set('operator', 'is before');
75
conditionBefore.set('value', view.end);
76
conditionBefore.set('smartView', this.args.viewList);
77
this.set('conditionBefore', conditionBefore);
78
79
this.addCondition(conditionAfter, true);
80
this.addCondition(conditionBefore, true);
81
82
this.args.fetchRecords({ page: 1 });
83
}
84
});
85
86
this.setEvent();
87
}
88
89
setEvent() {
90
if (!this.args.records) { return; }
91
92
const calendar = $(`#${this.calendarId}`);
93
calendar.fullCalendar('removeEvents');
94
95
this.args.records.forEach((appointment) => {
96
const event = {
97
id: appointment.get('id'),
98
title: appointment.get('forest-name'),
99
start: appointment.get('forest-start_date'),
100
end: appointment.get('forest-end_date')
101
};
102
103
calendar.fullCalendar('renderEvent', event, true);
104
});
105
}
106
107
@action
108
triggerSmartAction(...args) {
109
return triggerSmartAction(this, ...args);
110
}
111
112
@action
113
deleteRecords(...args) {
114
return deleteRecords(this, ...args);
115
}
116
}
Copied!
1
<style>
2
.calendar {
3
padding: 20px;
4
background: var(--color-beta-surface);
5
height:100%;
6
overflow: scroll;
7
}
8
.calendar .fc-toolbar.fc-header-toolbar .fc-left {
9
font-size: 14px;
10
font-weight: bold;
11
}
12
.calendar .fc-day-header {
13
padding: 10px 0;
14
background-color: var(--color-beta-secondary);
15
color: var(--color-beta-on-secondary_dark)
16
}
17
.calendar .fc-event {
18
background-color: var(--color-beta-secondary);
19
border: 1px solid var(--color-beta-on-secondary_border);
20
color: var(--color-beta-on-secondary_medium);
21
font-size: 14px;
22
}
23
.calendar .fc-day-grid-event {
24
background-color: var(--color-beta-info);
25
color: var(--color-beta-on-info);
26
font-size: 10px;
27
border: none;
28
padding: 2px;
29
}
30
.calendar .fc-day-number {
31
color: var(--color-beta-on-surface_medium);
32
}
33
.calendar .fc-other-month .fc-day-number {
34
color: var(--color-beta-on-surface_disabled);
35
}
36
.fc-left {
37
color: var(--color-beta-on-surface_dark);
38
}
39
</style>
40
41
<div id={{this.calendarId}} class="calendar" {{did-insert this.onInsert}}></div>
Copied!

Example: Shipping view

component.js
1
import Component from '@glimmer/component';
2
import { action, computed } from '@ember/object';
3