Create and manage Smart Actions

What is a Smart Action?

Sooner or later, you will need to perform actions on your data that are specific to your business. Moderating comments, generating an invoice, logging into a customer’s account or banning a user are exactly the kind of important tasks to unlock in order to manage your day-to-day operations.

On our Live Demo example, our companies collection has many examples of Smart Action. The simplest one is Mark as live.

If you're looking for information on native actions (CRUD), check out this page.

Creating a Smart action

In order to create a Smart action, you will first need to declare it in your code for a specific collection. Here we declare a Mark as Live Smart action for the companies collection.

SQL
Mongodb
Rails
SQL
/forest/companies.js
const { collection } = require('forest-express-sequelize');
collection('companies', {
actions: [{
name: 'Mark as Live'
}],
});
Mongodb
/forest/companies.js
const { collection } = require('forest-express-mongoose');
collection('companies', {
actions: [{
name: 'Mark as Live'
}],
});
Rails
/lib/forest_liana/collections/company.rb
class Forest::Company
include ForestLiana::Collection
collection :Company
action 'Mark as Live'
end

After declaring it, your Smart action will appear in the Smart actions tab within your collection settings.

A Smart action is displayed in the UI only if:

  • it is set as "visible" (see screenshot below) AND

  • in non-development environments, the user's role must grant the "trigger" permission

You must make the action visible there if you wish users to be able to see it.

It will then show in the actions dropdown button:

At this point, the Smart Action does nothing, because no route in your Admin backend handles the API call yet.

The Smart Action behavior is implemented separately from the declaration.

In the following example, we've implemented the Mark as live Smart Action, which simply changes a company's status to live.

SQL
Mongodb
Rails
SQL
/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
return new RecordsGetter(companies).getIdsFromRequest(req)
.then((companyIds) => {
return companies
.update({ status: 'live' }, { where: { id: companyIds }})
.then(() => {
res.send({ success: 'Company is now live!' });
});
});
});
...
module.exports = router;
Mongodb
/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
return new RecordsGetter(companies).getIdsFromRequest(req)
.then((companyIds) => {
return companies
.update({ status: 'live' }, { where: { id: companyIds }})
.then(() => {
res.send({ success: 'Company is now live!' });
});
});
});
...
module.exports = router;
Rails

The route declaration takes place in config/routes.rb.

/config/routes.rb
Rails.application.routes.draw do
# MUST be declared before the mount ForestLiana::Engine.
namespace :forest do
post '/actions/mark-as-live' => 'companies#mark_as_live'
end
mount ForestLiana::Engine => '/forest'
end

The business logic in this Smart Action is extremely simple. We only update here the attribute status of the companies to the value live:

/app/controllers/forest/companies_controller.rb
class Forest::CompaniesController < ForestLiana::SmartActionsController
def mark_as_live
company_id = ForestLiana::ResourcesGetter.get_ids_from_request(params).first
Company.update(company_id, status: 'live')
head :no_content
end
end

Note that Forest Admin takes care of the authentication thanks to the ForestLiana::SmartActionsController parent class controller.

You may have to add CORS headers to enable the domain app.forestadmin.com to trigger API call on your Application URL, which is on a different domain name (e.g. localhost:3000).

What's happening under the hood?

When you trigger the Smart Action from the UI, your browser will make an API call: POST /forest/actions/mask-as-live.

If you want to customize the API call, check the list of available options.

The payload of the HTTP request is based on a JSON API document. The data.attributes.ids key allows you to retrieve easily the selected records from the UI. The data.attributes.values key contains all the values of your input fields (handling input values). Other properties of data.attributes are used to manage the select all behavior.

payload example
{
"data": {
"attributes": {
"ids": ["1985"],
"values": {},
"collection_name": "companies",
...
},
"type": "custom-action-requests"
}
}

Should you want not to use the RecordsGetter and use request attributes directly instead, be very careful about edge cases (related data view, etc).

Available Smart Action options

Here is the list of available options to customize your Smart Action:

Name

Type

Description

name

string

Label of the action displayed in Forest Admin.

type

string

(optional) Type of the action. Can be bulk, global or single. Default is bulk.

fields

array of objects

(optional) Check the handling input values section.

download

boolean

(optional) If true, the action triggers a file download in the Browser. Default is false

endpoint

string

(optional) Set the API route to call when clicking on the Smart Action. Default is '/forest/actions/name-of-the-action-dasherized'

httpMethod

string

(optional) Set the HTTP method to use when clicking on the Smart Action. Default is POST.

Opening a form to ask input values

Very often, you will need to ask user inputs before triggering the logic behind a Smart Action. For example, you might want to specify a reason if you want to block a user account. Or set the amount to charge a user’s credit card.

SQL
Mongodb
Rails
SQL

On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs on the collection companies.

/forest/companies.js
const { collection } = require('forest-express-sequelize');
collection('companies', {
actions: [{
name: 'Upload Legal Docs',
type: 'single',
fields: [{
field: 'Certificate of Incorporation',
description: 'The legal document relating to the formation of a company or corporation.',
type: 'File',
isRequired: true
}, {
field: 'Proof of address',
description: '(Electricity, Gas, Water, Internet, Landline & Mobile Phone Invoice / Payment Schedule) no older than 3 months of the legal representative of your company',
type: 'File',
isRequired: true
}, {
field: 'Company bank statement',
description: 'PDF including company name as well as IBAN',
type: 'File',
isRequired: true
}, {
field: 'Valid proof of ID',
description: 'ID card or passport if the document has been issued in the EU, EFTA, or EEA / ID card or passport + resident permit or driving licence if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
type: 'File',
isRequired: true
}]
}]
});
/routes/companies.js
...
router.post('/actions/upload-legal-docs', permissionMiddlewareCreator.smartAction(),
(req, res) => {
// Get the current company id
let companyId = req.body.data.attributes.ids[0];
// Get the values of the input fields entered by the admin user.
let attrs = req.body.data.attributes.values;
let certificate_of_incorporation = attrs['Certificate of Incorporation'];
let proof_of_address = attrs['Proof of address'];
let company_bank_statement = attrs['Company bank statement'];
let passport_id = attrs['Valid proof of id'];
// The business logic of the Smart Action. We use the function
// UploadLegalDoc to upload them to our S3 repository. You can see the full
// implementation on our Forest Live Demo repository on Github.
return P.all([
uploadLegalDoc(companyId, certificate_of_incorporation, 'certificate_of_incorporation_id'),
uploadLegalDoc(companyId, proof_of_address, 'proof_of_address_id'),
uploadLegalDoc(companyId, company_bank_statement,'bank_statement_id'),
uploadLegalDoc(companyId, passport_id, 'passport_id'),
])
.then(() => {
// Once the upload is finished, send a success message to the admin user in the UI.
res.send({ success: 'Legal documents are successfully uploaded.' });
});
});
...
module.exports = router;
Mongodb

On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs on the collection companies.

/forest/companies.js
const { collection } = require('forest-express-mongoose');
collection('companies', {
actions: [{
name: 'Upload Legal Docs',
type: 'single',
fields: [{
field: 'Certificate of Incorporation',
description: 'The legal document relating to the formation of a company or corporation.',
type: 'File',
isRequired: true
}, {
field: 'Proof of address',
description: '(Electricity, Gas, Water, Internet, Landline & Mobile Phone Invoice / Payment Schedule) no older than 3 months of the legal representative of your company',
type: 'File',
isRequired: true
}, {
field: 'Company bank statement',
description: 'PDF including company name as well as IBAN',
type: 'File',
isRequired: true
}, {
field: 'Valid proof of ID',
description: 'ID card or passport if the document has been issued in the EU, EFTA, or EEA / ID card or passport + resident permit or driving licence if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
type: 'File',
isRequired: true
}],
});
/routes/companies.js
...
router.post('/actions/upload-legal-docs',
(req, res) => {
// Get the current company id
let companyId = req.body.data.attributes.ids[0];
// Get the values of the input fields entered by the admin user.
let attrs = req.body.data.attributes.values;
let certificate_of_incorporation = attrs['Certificate of Incorporation'];
let proof_of_address = attrs['Proof of address'];
let company_bank_statement = attrs['Company bank statement'];
let passport_id = attrs['Valid proof of id'];
// The business logic of the Smart Action. We use the function
// UploadLegalDoc to upload them to our S3 repository. You can see the full
// implementation on our Forest Live Demo repository on Github.
return P.all([
uploadLegalDoc(companyId, certificate_of_incorporation, 'certificate_of_incorporation_id'),
uploadLegalDoc(companyId, proof_of_address, 'proof_of_address_id'),
uploadLegalDoc(companyId, company_bank_statement,'bank_statement_id'),
uploadLegalDoc(companyId, passport_id, 'passport_id'),
])
.then(() => {
// Once the upload is finished, send a success message to the admin user in the UI.
res.send({ success: 'Legal documents are successfully uploaded.' });
});
});
...
module.exports = router;

Rails

On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs on the collection Company.

/lib/forest_liana/collections/company.rb
class Forest::Company
include ForestLiana::Collection
collection :Company
action 'Upload Legal Docs', type: 'single', fields: [{
field: 'Certificate of Incorporation',
description: 'The legal document relating to the formation of a company or corporation.',
type: 'File',
isRequired: true
}, {
field: 'Proof of address',
description: '(Electricity, Gas, Water, Internet, Landline & Mobile Phone Invoice / Payment Schedule) no older than 3 months of the legal representative of your company',
type: 'File',
isRequired: true
}, {
field: 'Company bank statement',
description: 'PDF including company name as well as IBAN',
type: 'File',
isRequired: true
}, {
field: 'Valid proof of ID',
description: 'ID card or passport if the document has been issued in the EU, EFTA, or EEA / ID card or passport + resident permit or driving licence if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
type: 'File',
isRequired: true
}]
end
/config/routes.rb
Rails.application.routes.draw do
# MUST be declared before the mount ForestLiana::Engine.
namespace :forest do
post '/actions/upload-legal-docs' => 'companies#upload_legal_docs'
end
mount ForestLiana::Engine => '/forest'
end
/app/controllers/forest/companies_controller.rb
class Forest::CompaniesController < ForestLiana::SmartActionsController
def upload_legal_doc(company_id, doc, field)
id = SecureRandom.uuid
Forest::S3Helper.new.upload(doc, "livedemo/legal/#{id}")
company = Company.find(company_id)
company[field] = id
company.save
Document.create({
file_id: company[field],
is_verified: true
})
end
def upload_legal_docs
# Get the current company id
company_id = ForestLiana::ResourcesGetter.get_ids_from_request(params).first
# Get the values of the input fields entered by the admin user.
attrs = params.dig('data', 'attributes', 'values')
certificate_of_incorporation = attrs['Certificate of Incorporation'];
proof_of_address = attrs['Proof of address'];
company_bank_statement = attrs['Company bank statement'];
passport_id = attrs['Valid proof of ID'];
# The business logic of the Smart Action. We use the function
# upload_legal_doc to upload them to our S3 repository. You can see the
# full implementation on our Forest Live Demo repository on Github.
upload_legal_doc(company_id, certificate_of_incorporation, 'certificate_of_incorporation_id')
upload_legal_doc(company_id, proof_of_address, 'proof_of_address_id')
upload_legal_doc(company_id, company_bank_statement, 'bank_statement_id')
upload_legal_doc(company_id, passport_id, 'passport_id')
# Once the upload is finished, send a success message to the admin user in the UI.
render json: { success: 'Legal documents are successfully uploaded.' }
end
end

Handling input values

Here is the list of available options to customize your input form.

Name

Type

Description

field

string

Label of the input field.

type

string or array

Type of your field.

  • string: Boolean, Date, Dateonly, Enum, File, Number, String

  • array: ['Enum'], ['Number'], ['String']

reference

string

(optional) Specify that the input is a reference to another collection. You must specify the primary key (ex: category.id).

enums

array of strings

(optional) Required only for the Enum type. This is where you list all the possible values for your input field.

description

string

(optional) Add a description for your admin users to help them fill correctly your form

isRequired

boolean

(optional) If true, your input field will be set as required in the browser. Default is false.

Making a form dynamic

This feature is only available from version 6.6.0 (forest-express-sequelize and forest-express-mongoose) / version 5.3.3 (forest-rails) and for single Smart actions.

Business logic often requires your forms to adapt to its context. Forest Admin makes this possible through a powerful way to extend your form's logic.

Change your form's data based on previous field values

Here's a typical example: Selecting a City within a list of cities from the Country you just selected. Then selecting a Zipcode within a list of zipcodes located in the City you just selected.

SQL
Mongodb
Rails
SQL
forest/customers.js
import {getEnumsFromDatabaseForThisRecord} from './my-own-helper'
import {getZipCodeFromCity} from ...
collection('customers', {
actions: [{
name: 'Send invoice',
type: 'single',
fields: [
{
field: 'country',
type: 'Enum',
enums: []
},
{
field: 'city',
type: 'String'
},
{
field: 'zip code',
type: 'String'
},
],
hooks: {
load: ({ fields, record }) => {
fields.country.enums = getEnumsFromDatabaseForThisRecord(record);
return fields;
},
change: {
city: ({ fields, record }) => {
fields['zip code'].value = getZipCodeFromCity(
record,
fields.city.value
);
return fields;
},
['zip code']: ({ fields, record }) => {
fields.city.value = getCityFromZipCode(
record,
fields['zip code'].value
);
return fields;
},
},
},
}],
fields: [],
segments: [],
});
Mongodb
forest/customers.js
import {getEnumsFromDatabaseForThisRecord} from './my-own-helper'
import {getZipCodeFromCity} from ...
collection('customers', {
actions: [{
name: 'Send invoice',
type: 'single',
fields: [
{
field: 'country',
type: 'Enum',
enums: []
},
{
field: 'city',
type: 'String'
},
{
field: 'zip code',
type: 'String'
},
],
hooks: {
load: ({ fields, record }) => {
fields.country.enums = getEnumsFromDatabaseForThisRecord(record);
return fields;
},
change: {
city: ({ fields, record }) => {
fields['zip code'].value = getZipCodeFromCity(
record,
fields.city.value
);
return fields;
},
['zip code']: ({ fields, record }) => {
fields.city.value = getCityFromZipCode(
record,
fields['zip code'].value
);
return fields;
},
},
},
}],
fields: [],
segments: [],
});
Rails
/lib/forest_liana/collections/company.rb
actions 'Send invoice',
type: 'single',
fields: [
{
field: 'country',
type: 'Enum',
enums: []
},
{
field: 'city',
type: 'String'
},
{
field: 'zip code',
type: 'String'
},
],
hooks: {
:load => -> (context){
context[:fields]['country'][:enums] = getEnumsFromDatabaseForThisRecord(context[:record])
return context[:fields]
},
:change => {
'city'=> -> (context){
context[:fields]['zip code'][:value] = getZipCodeFromCity(
context[:record],
context[:fields]['city'][:value]
)
return context[:fields]
},
'zip code'=> -> (context) {
context[:fields]['city'][:value] = getCityFromZipCode(
context[:record],
context[:fields]['zip code'][:value]
)
return context[:fields]
},
},
}

How does it work?

The hooks property receives a context object containing:

  • the fields object in its current state (containing also the current values)

  • the current record

fields must be returned (modified or unmodified). Note that fields is an object containing existing fields with properties described in this section.

The load hook is called when the form loads, allowing you to change its properties upon load.

The change hook is called whenever you interact with a field of the form.

To dynamically change a property within a load or change hook, just set it! For instance, setting a new description for the field city:

SQL
Mongodb
Rails
SQL
fields.city.description = "Please enter the name of your favorite city";
Mongodb
fields.city.description = "Please enter the name of your favorite city";
Rails
context[:fields]['city'][:value] = "Please enter the name of your favorite city"

As a result, the correct way to set a default value is using the value property within a load hook, as follows:

SQL
Mongodb
Rails
SQL
hooks: {
load: ({ fields, record }) => {
fields.country.value = "France";
return fields;
},
}
Mongodb
hooks: {
load: ({ fields, record }) => {
fields.country.value = "France";
return fields;
},
}
Rails
hooks: {
:load => -> (context){
context[:fields]['country'][:value] = "France"
return context[:fields]
},
}

Note that hooks don't yet allow to add new fields dynamically.

Prefill a form with default values

Forest Admin allows you to set default values of your form. In this example, we will prefill the form with data coming from the record itself (1), with just a few extra lines of code.

SQL
Mongodb
Rails
SQL
/forest/customers.js
const { collection } = require('forest-express-sequelize');
const models = require('../models/');
const _ = require('lodash');
collection('customers', {
actions: [{
name: 'Generate invoice',
download: true
}, {
name: 'Charge credit card',
type: 'single',
fields: [{
field: 'amount',
isRequired: true,
description: 'The amount (USD) to charge the credit card. Example: 42.50',
type: 'Number'
}, {
field: 'description',
isRequired: true,
description: 'Explain the reason why you want to charge manually the customer here',
type: 'String'
}, {
// we added a field to show the full potential of prefilled values in this example
field: 'stripe_id',
isRequired: true,
type: 'String'
}],
hooks: {
load: ({ fields, record }) => {
fields.amount.value = 4520;
fields.stripe_id.value = record.stripe_id;
return fields;
},
},
}],
...
});
Mongodb
/forest/customers.js
const { collection } = require('forest-express-mongoose');
const models = require('../models/');
const _ = require('lodash');
collection('Customer', {
actions: [{
name: 'Generate invoice',
download: true
}, {
name: 'Charge credit card',
type: 'single',
fields: [{
field: 'amount',
isRequired: true,
description: 'The amount (USD) to charge the credit card. Example: 42.50',
type: 'Number'
}, {
field: 'description',
isRequired: true,
description: 'Explain the reason why you want to charge manually the customer here',
type: 'String'
}, {
// we added a field to show the full potential of prefilled values in this example
field: 'stripe_id',
isRequired: true,
type: 'String'
}],
hooks: {
load: ({ fields, record }) => {
fields.amount.value = 4520;
fields.stripe_id.value = record.stripe_id;
return fields;
},
},
}],
...
});
Rails
hooks: {
:load => -> (context){
context[:fields]['amount'][:value] = 4520
context[:fields]['stripe_id'][:value] = context[:record]['stripe_id']
return context[:fields]
},
}

Customizing response

Default success notification

Returning a 204 status code to the HTTP request of the Smart Action shows the default notification message in the browser.

On our Live Demo example, if our Smart Action Mark as Live route is implemented like this:

/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
// ...
res.status(204).send();
});
...

We will see a success message in the browser:

Custom success notification

If we return a 200 status code with an object { success: '...' } as the payload like this…

SQL
Mongodb
Rails
SQL
/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
// ...
res.send({ success: 'Company is now live!' });
});
...
Mongodb
/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
// ...
res.send({ success: 'Company is now live!' });
});
...
Rails
class Forest::CompaniesController < ForestLiana::SmartActionsController
def mark_as_live
# ...
render json: { success: 'Company is now live!' }
end
end

… the success notification will look like this:

Custom error notification

Finally, returning a 400 status code allows you to return errors properly.

SQL
Mongodb
Rails
SQL
/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
// ...
res.status(400).send({ error: 'The company was already live!' });
});
...
Mongodb
/routes/companies.js
...
router.post('/actions/mark-as-live', permissionMiddlewareCreator.smartAction(), (req, res) => {
// ...
res.status(400).send({ error: 'The company was already live!' });
});
...
Rails
/app/controllers/forest/companies_controller.rb
class Forest::CompaniesController < ForestLiana::SmartActionsController
def mark_as_live
# ...
render status: 400, json: { error: 'The company was already live!' }
end
end

Custom HTML response

You can also return a HTML page as a response to give more feedback to the admin user who has triggered your Smart Action. To do this, you just need to return a 200 status code with an object { html: '...' }.

On our Live Demo example, we’ve created a Charge credit card Smart Action on the Collection customersthat returns a custom HTML response.

SQL
Mongodb
Rails
SQL
/forest/companies.js
const { collection } = require('forest-express-sequelize');
collection('customers', {
actions: [{
name: 'Charge credit card',
type: 'single',
fields: [{
field: 'amount',
isRequired: true,
description: 'The amount (USD) to charge the credit card. Example: 42.50',
type: 'Number'
}, {
field: 'description',
isRequired: true,
description: 'Explain the reason why you want to charge manually the customer here',
type: 'String'
}]
}]
});
/routes/customers.js
...
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
router.post('/actions/charge-credit-card', permissionMiddlewareCreator.smartAction(), (req, res) => {
let customerId = req.body.data.attributes.ids[0];
let amount = req.body.data.attributes.values.amount * 100;
let description = req.body.data.attributes.values.description;
return customers
.findById(customerId)
.then((customer) => {
return stripe.charges.create({
amount: amount,
currency: 'usd',
customer: customer.stripe_id,
description: description
});
})
.then((response) => {
res.send({
html: `
<p class="c-clr-1-4 l-mt l-mb">\$${response.amount / 100} USD has been successfuly charged.</p>
<strong class="c-form__label--read c-clr-1-2">Credit card</strong>
<p class="c-clr-1-4 l-mb">**** **** **** ${response.source.last4}</p>
<strong class="c-form__label--read c-clr-1-2">Expire</strong>
<p class="c-clr-1-4 l-mb">${response.source.exp_month}/${response.source.exp_year}</p>
<strong class="c-form__label--read c-clr-1-2">Card type</strong>
<p class="c-clr-1-4 l-mb">${response.source.brand}</p>
<strong class="c-form__label--read c-clr-1-2">Country</strong>
<p class="c-clr-1-4 l-mb">${response.source.country}</p>
`
});
});
});
...
module.exports = router;
Mongodb
/forest/companies.js
const { collection } = require('forest-express-mongoose');
collection('Customer', {
actions: [{
name: 'Charge credit card',
type: 'single',
fields: [{
field: 'amount',
isRequired: true,
description: 'The amount (USD) to charge the credit card. Example: 42.50',
type: 'Number'
}, {
field: 'description',
isRequired: true,
description: 'Explain the reason why you want to charge manually the customer here',
type: 'String'
}]
}]
});
/routes/customers.js
...
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);
router.post('/actions/charge-credit-card', (req, res) => {
let customerId = req.body.data.attributes.ids[0];
let amount = req.body.data.attributes.values.amount * 100;
let description = req.body.data.attributes.values.description;
return Customer
.findById(customerId)
.then((customer) => {
return stripe.charges.create({
amount: amount,
currency: 'usd',
customer: customer.stripe_id,
description: description
});
})
.then((response) => {
res.send({
html: `
<p class="c-clr-1-4 l-mt l-mb">\$${response.amount / 100} USD has been successfuly charged.</p>
<strong class="c-form__label--read c-clr-1-2">Credit card</strong>
<p class="c-clr-1-4 l-mb">**** **** **** ${response.source.last4}</p>
<strong class="c-form__label--read c-clr-1-2">Expire</strong>
<p class="c-clr-1-4 l-mb">${response.source.exp_month}/${response.source.exp_year}</p>
<strong class="c-form__label--read c-clr-1-2">Card type</strong>
<p class="c-clr-1-4 l-mb">${response.source.brand}</p>
<strong class="c-form__label--read c-clr-1-2">Country</strong>
<p class="c-clr-1-4 l-mb">${response.source.country}</p>
`
});
});
});
...
module.exports = router;

Rails
/lib/forest_liana/collections/customer.rb
class Forest::Customer
include ForestLiana::Collection
collection :Customer
action 'Charge credit card', type: 'single', fields: [{
field: 'amount',
isRequired: true,
description: 'The amount (USD) to charge the credit card. Example: 42.50',
type: 'Number'
}, {
field: 'description',
isRequired: true,
description: 'Explain the reason why you want to charge manually the customer here',
type: 'String'
}]
end
/config/routes.rb
Rails.application.routes.draw do
# MUST be declared before the mount ForestLiana::Engine.
namespace :forest do
post '/actions/charge-credit-card' => 'customers#charge_credit_card'
end
mount ForestLiana::Engine => '/forest'
end
/app/controllers/forest/customers_controller.rb
class Forest::CustomersController < ForestLiana::SmartActionsController
def charge_credit_card
customer_id = ForestLiana::ResourcesGetter.get_ids_from_request(params).first
amount = params.dig('data', 'attributes', 'values', 'amount').to_i
description = params.dig('data', 'attributes', 'values', 'description')
customer = Customer.find(customer_id)
response = Stripe::Charge.create(
amount: amount * 100,
currency: 'usd',
customer: customer.stripe_id,
description: description
)
render json: { html: <<EOF
<p class="c-clr-1-4 l-mt l-mb">$#{response.amount / 100.0} USD has been successfuly charged.</p>
<strong class="c-form__label--read c-clr-1-2">Credit card</strong>
<p class="c-clr-1-4 l-mb">**** **** **** #{response.source.last4}</p>
<strong class="c-form__label--read c-clr-1-2">Expire</strong>
<p class="c-clr-1-4 l-mb">#{response.source.exp_month}/#{response.source.exp_year}</p>
<strong class="c-form__label--read c-clr-1-2">Card type</strong>
<p class="c-clr-1-4 l-mb">#{response.source.brand}</p>
<strong class="c-form__label--read c-clr-1-2">Country</strong>
<p class="c-clr-1-4 l-mb">#{response.source.country}</p>
EOF
}
end
end

Setting up a webhook

After a smart action you can set up a HTTP (or HTTPS) callback - a webhook - to forward information to other applications. To set up a webhook all you have to do is to add a webhookobject in the response of your action.

SQL
Mongodb
Rails
SQL
response.send({
webhook: { // This is the object that will be used to fire http calls.
url: 'http://my-company-name', // The url of the company providing the service.
method: 'POST', // The method you would like to use (typically a POST).
headers: { }, // You can add some headers if needed (you can remove it).
body: { // A body to send to the url (only JSON supported).
adminToken: 'your-admin-token',
},
},
});
Mongodb
response.send({
webhook: { // This is the object that will be used to fire http calls.
url: 'http://my-company-name', // The url of the company providing the service.
method: 'POST', // The method you would like to use (typically a POST).
headers: { }, // You can add some headers if needed (you can remove it).
body: { // A body to send to the url (only JSON supported).
adminToken: 'your-admin-token',
},
},
});
Rails
render json: {
webhook: { # This is the object that will be used to fire http calls.
url: 'http://my-company-name', # The url of the company providing the service.
method: 'POST', # The method you would like to use (typically a POST).
headers: {}, # You can add some headers if needed (you can remove it).
body: { # A body to send to the url (only JSON supported).
adminToken: 'your-admin-token',
}
}
}

Webhooks are commonly used to perform smaller requests and tasks, like sending emails or impersonating a user.

Another interesting use of this is automating SSO authentication into your external apps.

Downloading a file

SQL
Mongodb
Rails
SQL

On our Live Demo, the collection customers has a Smart Action Generate invoice. In this use case, we want to download the generated PDF invoice after clicking on the action. To indicate a Smart Action returns something to download, you have to enable the option download.

/forest/customers.js
const { collection } = require('forest-express-sequelize');
collection('customers', {
actions: [{
name: 'Generate invoice',
download: true // If true, the action triggers a file download in the Browser.
}]
});
/routes/customers.js
...
router.post('/actions/generate-invoice', permissionMiddlewareCreator.smartAction(),
(req, res) => {
let options = {
root: __dirname + '/../public/',
dotfiles: 'deny',
headers: {
'Access-Control-Expose-Headers': 'Content-Disposition',
'Content-Disposition': 'attachment; filename="invoice-2342.pdf"'
}
};
let fileName = 'invoice-2342.pdf';
res.sendFile(fileName, options, (error) => {
if (error) { next(error); }
});
});
...
module.exports = router;
Mongodb

On our Live Demo, the collection customers has a Smart Action Generate invoice. In this use case, we want to download the generated PDF invoice after clicking on the action. To indicate a Smart Action returns something to download, you have to enable the option download.

/forest/customers.js
const { collection } = require('forest-express-mongoose');
collection('Customer', {
actions: [{
name: 'Generate invoice',
download: true // If true, the action triggers a file download in the Browser.
}]
});
/routes/customers.js
...
router.post('/actions/generate-invoice', Liana.ensureAuthenticated,
(req, res) => {
let options = {
root: __dirname + '/../public/',
dotfiles: 'deny',
headers: {
'Access-Control-Expose-Headers': 'Content-Disposition',
'Content-Disposition': 'attachment; filename="invoice-2342.pdf"'
}
};
let fileName = 'invoice-2342.pdf';
res.sendFile(fileName, options, (error) => {
if (error) { next(error); }
});
});
...
module.exports = router;
Rails

On our Live Demo, the collection Customer has a Smart Action Generate invoice. In this use case, we want to download the generated PDF invoice after clicking on the action. To indicate a Smart Action returns something to download, you have to enable the option download.

Don’t forget to expose the Content-Disposition header in the CORS configuration (as shown in the code below) to be able to customize the filename to download.

/lib/forest_liana/collections/customer.rb
class Forest::Customer
include ForestLiana::Collection
collection :Customer
action 'Generate invoice', download: true
end
/config/routes.rb
Rails.application.routes.draw do
# MUST be declared before the mount ForestLiana::Engine.
namespace :forest do
post '/actions/generate-invoice' => 'customers#generate_invoice'
end
mount ForestLiana::Engine => '/forest'
end
/config/application.rb
module LiveDemoRails
class Application < Rails::Application
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options],
# you MUST expose the Content-Disposition header to customize the file to download.
expose: ['Content-Disposition']
end
end
end
end
/app/controllers/forest/customers_controller.rb
class Forest::CustomersController < ForestLiana::SmartActionsController
def generate_invoice
data = open("#{File.dirname(__FILE__)}/../../../public/invoice-2342.pdf" )
send_data data.read, filename: 'invoice-2342.pdf', type: 'application/pdf', disposition: 'attachment'
end
end

Want to upload your files to Amazon S3? Check out this this Woodshop tutorial.

If you want to create an action accessible from the details or the summary view of a record involving related data, this section may interest you.

In the example below, the “Add new transaction” action (1) is accessible from the summary view. This action creates a new transaction and automatically refresh the “Emitted transactions” related data section (2) to see the new transaction.

SQL
Mongodb
Rails
SQL

Below is the sample code. We use faker to generate random data in our example. Remember to install it if you wish to use it (npm install faker).

/forest/companies.js
const { collection } = require('forest-express-sequelize');
collection('companies', {
actions: [{
name: 'Add new transaction',
description: 'Name of the company who will receive the transaction.',
fields: [{
field: 'Beneficiary company',
description: 'Name of the company who will receive the transaction.',
reference: 'companies.id'
},{
field: 'Amount',
type: 'Number'
}]
}],
});
/routes/companies.js
...
const faker = require('faker');
router.post('/actions/add-new-transaction', permissionMiddlewareCreator.smartAction(),
(req, res) => {
let emitterCompanyId = req.body.data.attributes.ids[0]
let beneficiaryCompanyId = req.body.data.attributes.values['Beneficiary company']
let amount = req.body.data.attributes.values['Amount']
return transactions
.create({
emitter_company_id: