Use a Smart Action Form
Please be sure of your agent type and version and pick the right documentation accordingly.
This is the documentation of the forest-express-sequelize
and forest-express-mongoose
Node.js agents that will soon reach end-of-support.
forest-express-sequelize
v9 and forest-express-mongoose
v9 are replaced by @forestadmin/agent
v1.
Please check your agent type and version and read on or switch to the right documentation.
This is still the latest Ruby on Rails documentation of the forest_liana
agent, you’re at the right place, please read on.
This is the documentation of the django-forestadmin
Django agent that will soon reach end-of-support.
If you’re using a Django agent, notice that django-forestadmin
v1 is replaced by forestadmin-agent-django
v1.
If you’re using a Flask agent, go to the forestadmin-agent-flask
v1 documentation.
Please check your agent type and version and read on or switch to the right documentation.
This is the documentation of the forestadmin/laravel-forestadmin
Laravel agent that will soon reach end-of-support.
If you’re using a Laravel agent, notice that forestadmin/laravel-forestadmin
v1 is replaced by forestadmin/laravel-forestadmin
v3.
If you’re using a Symfony agent, go to the forestadmin/symfony-forestadmin
v1 documentation.
Please check your agent type and version and read on or switch to the right documentation.
Use a Smart Action Form
We've just introduced Smart actions: they're great because you can execute virtually any business logic. However, there is one big part missing: how do you let your users provide more information or have interaction when they trigger the Smart action? In short, you need to open a Smart Action Form.
Opening a Smart Action Form
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.
On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs
on the collection companies
.
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 license if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
type: 'File',
isRequired: true,
},
],
},
],
});
const { PermissionMiddlewareCreator } = require('forest-express-sequelize');
const permissionMiddlewareCreator = new PermissionMiddlewareCreator('companies');
...
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;
On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs
on the collection companies
.
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 license if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
type: 'File',
isRequired: true
}],
});
...
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;
On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs
on the collection Company
.
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',
is_required: 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',
is_required: true
}, {
field: 'Company bank statement',
description: 'PDF including company name as well as IBAN',
type: 'File',
is_required: 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 license if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
type: 'File',
is_required: true
}]
end
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
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, forest_user).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
On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs
on the collection Company
.
from django_forest.utils.collection import Collection
from app.models import Company
class CompanyForest(Collection):
def load(self):
self.actions = [{
'name': 'Upload Legal Docs',
'fields': [
{
'field': 'Certificate of Incorporation',
'description': 'The legal document relating to the formation of a company or corporation.',
'isRequired': True,
'type': 'File'
},
{
'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',
'isRequired': True,
'type': 'File'
},
{
'field': 'Company bank statement',
'description': 'PDF including company name as well as IBAN',
'isRequired': True,
'type': 'File'
},
{
'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 license if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company',
'isRequired': True,
'type': 'File'
},
],
}]
Collection.register(CompanyForest, Company)
Ensure the file app/forest/__init__.py exists and contains the import of the previous defined class :
from app.forest.companies import CompanyForest
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from . import views
app_name = 'app'
urlpatterns = [
path('/actions/upload-legal-docs', csrf_exempt(views.UploadLegalDocsView.as_view()), name='upload-legal-docs'),
]
from django.http import JsonResponse
from django_forest.utils.views.action import ActionView
class UploadLegalDocsView(ActionView):
def upload_legal_doc(company_id, doc, field):
# FIXME
pass
def post(self, request, *args, **kwargs):
params = request.GET.dict()
body = self.get_body(request.body)
ids = self.get_ids_from_request(request, self.Model)
# Get the current company id
company_id = ids[0]
# Get the values of the input fields entered by the admin user.
attrs = body['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.
self.upload_legal_doc(company_id, certificate_of_incorporation, 'certificate_of_incorporation_id')
self.upload_legal_doc(company_id, proof_of_address, 'proof_of_address_id')
self.upload_legal_doc(company_id, company_bank_statement, 'bank_statement_id')
self.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.
return JsonResponse({'success': 'Legal documents are successfully uploaded.'})
On our Live Demo example, we’ve defined 4 input fields on the Smart Action Upload Legal Docs
on the collection Company
.
The 2nd parameter of the SmartAction
method is not required. If you don't fill it, the name of your smartAction will be the name of your method that wrap it.
<?php
namespace App\Models;
use ForestAdmin\LaravelForestAdmin\Services\Concerns\ForestCollection;
use ForestAdmin\LaravelForestAdmin\Services\SmartFeatures\SmartAction;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
/**
* Class Company
*/
class Company extends Model
{
use HasFactory, ForestCollection;
/**
* @return SmartAction
*/
public function UploadLegalDocs(): SmartAction
{
return $this->smartAction('single', 'Upload Legal Docs')
->addField(
[
'field' => 'Certificate of Incorporation',
'type' => 'File',
'is_required' => true,
'description' => 'The legal document relating to the formation of a company or corporation.'
]
)
->addField(
[
'field' => 'Proof of address',
'type' => 'File',
'is_required' => false,
'description' => '(Electricity, Gas, Water, Internet, Landline & Mobile Phone Invoice / Payment Schedule) no older than 3 months of the legal representative of your company'
]
)
->addField(
[
'field' => 'Company bank statement',
'type' => 'File',
'is_required' => true,
'description' => 'PDF including company name as well as IBAN'
]
)
->addField(
[
'field' => 'Valid proof of ID',
'type' => 'File',
'is_required' => true,
'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 license if the document has been issued outside the EU, EFTA, or EEA of the legal representative of your company'
]
);
}
}
Route::post('forest/smart-actions/company_upload-legal-docs', [CompaniesController::class, 'uploadLegalDocs']);
<?php
namespace App\Http\Controllers;
use App\Models\Company;
use ForestAdmin\LaravelForestAdmin\Http\Controllers\ForestController;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Storage;
/**
* Class CompaniesController
*/
class CompaniesController extends ForestController
{
/**
* @return JsonResponse
*/
public function uploadLegalDocs()
{
$companyId = request()->input('data.attributes.ids')[0];
$files = request()->input('data.attributes.values');
foreach ($files as $key => $file)
{
$data = explode(";base64,", $file);
Storage::disk('s3')->put($key . '-' . $companyId, base64_decode($data[1]));
}
return response()->json(
[
'success' => 'Legal documents are successfully uploaded.',
]
);
}
}
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.
|
reference | string | (optional) Specify that the input is a reference to another collection. You must specify the primary key (ex: |
enums | array of strings | (optional) Required only for the |
description | string | (optional) Add a description for your admin users to help them fill correctly your form |
isRequired | boolean | (optional) If |
hook | string | (optional) Specify the change hook. If specified the corresponding hook is called when the input change |
widget | string | (optional) The following widgets are available to your smart action fields ( |
Making a form dynamic with hooks
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.
To make Smart Action Forms dynamic, we've introduced the concept of hooks: hooks allow you to run some logic upon a specific event.
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.
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.
const { collection } = require('forest-express-sequelize');
const { customers } = require('../models');
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'
}, {
// we added a field to show the full potential of prefilled values in this example
field: 'stripe_id',
isRequired: true,
type: 'String'
}],
hooks: {
load: async ({ fields, request }) => {
const amount = fields.find(field => field.field === 'amount');
const stripeId = fields.find(field => field.field === 'stripe_id');
amount.value = 4520;
const id = request.body.data.attributes.ids[0];
const customer = await customers.findByPk(id);
stripeId.value = customer.stripe_id;
return fields;
},
},
}],
...
});
const { collection } = require('forest-express-mongoose');
const { customers } = require('../models');
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'
}, {
// we added a field to show the full potential of prefilled values in this example
field: 'stripe_id',
isRequired: true,
type: 'String'
}],
hooks: {
load: async ({ fields, request }) => {
const amount = fields.find(field => field.field === 'amount');
const stripeId = fields.find(field => field.field === 'stripe_id');
amount.value = 4520;
const id = request.body.data.attributes.ids[0];
const customer = await customers.findByPk(id);
stripeId.value = customer.stripe_id;
return fields;
},
},
}],
...
});
class Forest::Customers
include ForestLiana::Collection
collection :Customers
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'
}, {
# we added a field to show the full potential of prefilled values in this example
field: 'stripe_id',
isRequired: true,
type: 'String'
}],
:hooks => {
:load => -> (context) {
amount = context[:fields].find{|field| field[:field] == 'amount'}
stripeId = context[:fields].find{|field| field[:field] == 'stripe_id'}
amount[:value] = 4520;
id = context[:params][:data][:attributes][:ids][0];
customer = Customers.find(id);
stripeId[:value] = customer['stripe_id'];
return context[:fields];
}
}
...
end
import json
from django_forest.utils.collection import Collection
from app.models import Company
class CompanyForest(Collection):
def load(self):
self.actions = [{
'name': 'Charge credit card',
'fields': [
{
'field': 'amount',
'description': 'The amount (USD) to charge the credit card. Example: 42.50',
'isRequired': True,
'type': 'Number'
},
{
'field': 'description',
'description': 'Explain the reason why you want to charge manually the customer here',
'isRequired': True,
'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': self.charge_credit_card_load,
},
}]
def charge_credit_card_load(fields, request, *args, **kwargs):
amount = next((x for x in fields if x['field'] == 'amount'), None)
stripeId = next((x for x in fields if x['field'] == 'stripe_id'), None)
amount['value'] = 4520;
body_unicode = request.body.decode('utf-8')
body = json.loads(body_unicode)
id = body['data']['attributes']['ids'][0]
customer = Customers.objects.get(pk=id)
stripeId['value'] = customer['stripe_id']
return fields
Collection.register(CompanyForest, Company)
<?php
namespace App\Models;
use ForestAdmin\LaravelForestAdmin\Services\Concerns\ForestCollection;
use ForestAdmin\LaravelForestAdmin\Services\SmartFeatures\SmartAction;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
/**
* Class Customer
*/
class Customer extends Model
{
use HasFactory, ForestCollection;
/**
* @return SmartAction
*/
public function chargeCreditCard(): SmartAction
{
return $this->smartAction('single', 'Charge credit card')
->addField(
[
'field' => 'amount',
'type' => 'Number',
'is_required' => true,
'description' => 'The amount (USD) to charge the credit card. Example: 42.50'
]
)
->addField(
[
'field' => 'description',
'type' => 'String',
'is_required' => true,
'description' => 'Explain the reason why you want to charge manually the customer here'
]
)
->addField(
[
'field' => 'stripe_id',
'type' => 'String',
'is_required' => true,
]
)
->load(
function () {
$customer = Customer::find(request()->input('data.attributes.ids')[0]);
$fields = $this->getFields();
$fields['amount']['value'] = 4250;
$fields['stripe_id']['value'] = $customer->stripe_id;
return $fields;
}
);
}
}
Making a field read-only
To make a field read only, you can use the isReadOnly
property:
Name | Type | Description |
---|---|---|
| boolean | (optional) If |
Combined with the load hook feature, this can be used to make a field read-only dynamically:
const { customers } = require('../models');
collection('customers', {
actions: [
{
name: 'Some action',
type: 'single',
fields: [
{
field: 'country',
type: 'String',
isReadOnly: true,
},
{
field: 'city',
type: 'String',
},
],
hooks: {
load: async ({ fields, request }) => {
const country = fields.find((field) => field.field === 'country');
country.value = 'France';
const id = request.body.data.attributes.ids[0];
const customer = await customers.findById(id);
// If customer country is not France, empty field and make it editable
if (customer.country !== 'France') {
country.value = '';
country.isReadOnly = false;
}
return fields;
},
},
},
],
fields: [],
segments: [],
});
Change your form's data based on previous field values
This feature is only available from version 8.0.0 (forest-express-sequelize
and forest-express-mongoose
) / version 7.0.0 (forest-rails
) .
Here's a typical example: Selecting a City within a list of cities from the Country you just selected. Then selecting a Zip code within a list of zip codes located in the City you just selected.
const { getEnumsFromDatabaseForThisRecord } = require('./my-own-helper');
const { getZipCodeFromCity } = require('...');
const { collection } = require('forest-express-sequelize');
const { customers } = require('../models');
collection('customers', {
actions: [
{
name: 'Send invoice',
type: 'single',
fields: [
{
field: 'country',
type: 'Enum',
enums: [],
},
{
field: 'city',
type: 'String',
hook: 'onCityChange',
},
{
field: 'zip code',
type: 'String',
hook: 'onZipCodeChange',
},
],
hooks: {
load: async ({ fields, request }) => {
const country = fields.find((field) => field.field === 'country');
const id = request.body.data.attributes.ids[0];
const customer = await customers.findByPk(id);
country.enums = getEnumsFromDatabaseForThisRecord(customer);
return fields;
},
change: {
onCityChange: async ({ fields, request, changedField }) => {
const zipCode = fields.find((field) => field.field === 'zip code');
const id = request.body.data.attributes.ids[0];
const customer = await customers.findByPk(id);
zipCode.value = getZipCodeFromCity(customer, changedField.value);
return fields;
},
onZipCodeChange: async ({ fields, request, changedField }) => {
const city = fields.find((field) => field.field === 'city');
const id = request.body.data.attributes.ids[0];
const customer = await customers.findByPk(id);
city.value = getCityFromZipCode(customer, changedField.value);
return fields;
},
},
},
},
],
fields: [],
segments: [],
});
const { getEnumsFromDatabaseForThisRecord } = require('./my-own-helper');
const { getZipCodeFromCity } = require('...');
const { collection } = require('forest-express-mongoose');
const { customers } = require('../models');
collection('customers', {
actions: [
{
name: 'Send invoice',
type: 'single',
fields: [
{
field: 'country',
type: 'Enum',
enums: [],
},
{
field: 'city',
type: 'String',
hook: 'onCityChange',
},
{
field: 'zip code',
type: 'String',
hook: 'onZipCodeChange',
},
],
hooks: {
load: async ({ fields, request }) => {
const country = fields.find((field) => field.field === 'country');
const id = request.body.data.attributes.ids[0];
const customer = await customers.findById(id);
country.enums = getEnumsFromDatabaseForThisRecord(customer);
return fields;
},
change: {
onCityChange: async ({ fields, request, changedField }) => {
const zipCode = fields.find((field) => field.field === 'zip code');
const id = request.body.data