How to specify a formula in an Express object (database) that calculates the value of certain attributes (derived fields) from user provided attributes (input fields)?

Hi all, I’ve got some Express objects with attributes that in an ordinary database would be derived fields with values calculated using a formula.

For example:
inputs: price and cost.
derived attribute: margin = price - cost
derived attribute: markup = price / cost
derived attribute: margin_pct = margin / price

If it can’t be done on the front end (forms), happy to be pointed to a solution that works on the backend.

Thanks a lot!
A.E.

My question would be why would you store this in the database. Surely you just output these in PHP when you print the results of the express data.

I had a similar requirement for a Form Reform application and ended up adding a maths engine to my addon.

At first I thought like @TMDesigns, why store derived values? Then realised it was much simpler to search and sort results if the calculated value was saved with the form.

Hence whilst @assadebrahim’s intended design may not be optimum for the data, maybe it simplifies things later on.

(Building the maths engine into Form Reform Display is on my roadmap)

A few reasons:

  1. Certain derived values are best stored in the table to make it easy to run aggregate operations on various subsets. In the commercial example, e.g. margin of a subset of the SKUs.

  2. As @JohnthFish correctly wrote, storing certain derived values in the table makes it easier to provide listings sorted in a ‘useful’ order. In the commercial example, sorting the list by margin allows either focusing on high margin items or asking for action to improve the low margin items.

Is there an easy way to do this?

Thanks!
A.E.

If it can be calculated on form save, you can plug to on_express_entry_saved event.
Inside event, check if current express object = your_object and do the math there.

Edit: Added link to documentation: