This example shows you how to implement a smart field that displays HTML.
Here a MoviehasOnemovieCharacteristic.
On the movies collection, we want to implement a smart field (called characteristics) that will display all the characteristics of a movie.
Requirements
An admin backend running on forest-express-sequelize
How it works
Directory: /models
This directory contains the movies.js and movie-characteristics.js files where the models movies and movieCharacteristics are defined.
This directory contains the movies.js file where the smart field characteristics is implemented. The smart field returns an html-formatted list of the movie characteristics as a string.
/forest/programs.js
const { collection } =require('forest-express-sequelize');constsequelize=require('sequelize');constmodels=require('../models');collection('movies', { fields: [ { field:'characteristics', type:'String',get: (movie) => {// check if the movie has a related characteristics record to return smtg or notif (movie.movieCharacteristic) {// list all your fields from the movieCharacteristics collection you want to displayconstcharacteristicsNameList= ['language','gore','drugs','graphicViolence','nudity']; // create empty string which will be filled with a div per field listed above - this string will be the value returned
let characteristicsList ='';// add style that will be used to display the movie_characteristics infoconstcharacteristicsDivStyle='margin: 24px 0px; color: #415574'; const characteristicsNameStyle = 'padding: 6px 16px; margin: 12px; background-color:#b5c8d05e; border-radius: 6px';
constcharacteristicsValueStyleRed='padding: 6px 12px; background-color:#ff7f7f87; border-radius: 6px';constcharacteristicsValueStyleGreen='padding: 6px 12px; background-color:#7FFF7F; border-radius: 6px';// iterate over the list of movie characteristics fieldsfor (index =0; index <characteristicsNameList.length; index++) {constfieldName= characteristicsNameList[index];// check if the value of the field is 0 or 1 to add the relevant style (default is 0)let characteristicsValueStyle = characteristicsValueStyleRed;if (movie.movieCharacteristic[fieldName] ===true) { characteristicsValueStyle = characteristicsValueStyleGreen; }// insert the div with the field info to the string that will be returned characteristicsList +=`<div style="${characteristicsDivStyle}"> <span style="${characteristicsNameStyle}">${fieldName}</span> <span style="${characteristicsValueStyle}">${movie.movieCharacteristic[fieldName]}</span> </div>`; }return characteristicsList; } }, }});
You will need to select the rich text editor widget for this field in your collection settings to display the string returned by the smart field in html format.