Please check your agent type and version and read on or switch to the right documentation.
Create a record with a multiselect through a many-to-many relationship
Context: In this case, a card has many expense categories through a many to many relationships, using a join table (card expense categories). We want to be able to create a card, selecting the categories, and creating the card expense categories at the same time.
Implementation:
We will use a smart action form with a hook to retrieve the categories as values for the multi select.
Then we implement the creation of cards and expenseCategories in the form.
constexpress=require('express');const { PermissionMiddlewareCreator } =require('forest-express-sequelize');const {cards,cardExpenseCategories,expenseCategories,} =require('../models');constrouter=express.Router();constpermissionMiddlewareCreator=newPermissionMiddlewareCreator('cards');// This file contains the logic of every route in Forest Admin for the collection cards:// - Native routes are already generated but can be extended/overridden - Learn how to extend a route here: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/routes/extend-a-route>// - Smart action routes will need to be added as you create new Smart Actions - Learn how to create a Smart Action here: <https://docs.forestadmin.com/documentation/v/v6/reference-guide/actions/create-and-manage-smart-actions>//...//Smart action - Create a cardrouter.post('/actions/create-card',permissionMiddlewareCreator.smartAction(), (req, res) => {let attrs =req.body.data.attributes.values; categories_attrs = attrs['categories']; attrs = { name: attrs['name'], userId: attrs['user'] };return cards.create(attrs).then((card) => {categories_attrs.forEach((category) => {return expenseCategories.findOne({ where: { title: category } }).then((expenseCategory) =>cardExpenseCategories.create({ cardId:card.id, expenseCategoryId:expenseCategory.id, }) ); }); }).then(() => {res.send({ success:'Your card is created!', refresh: { relationships: ['cardExpensesCategories'] }, }); }); });