Formulas

Formulae in Saltcorn are JavaScript expressions based on the current database row. This means that you can use the values in the current row to:

  • Calculate and display a derived value
  • Conditionally hide or show content
  • Change display properties 
  • Change the state of a view that is embedded on a different view or a page
  • Change a link URL
  • Change the text in a link
  • Set which roows are displayed
  • Change the options in a drop-down
  • Create a calculated field (stored or not stored)
  • Express that some rows are owned by users according to an expression that is more complicated than a simple field

The formula must return a value which is then used depending on where the formula is entered. Some examples:

  • You want to use a field in the current row to calculate a URL that you are linking to. An example Formula for an internal link could be: '/view/mypage?id='+id, and for an external URL 'https://en.wikipedia.org/wiki/'+wiki_page_name
  • You want to use a field name is the label for a link. If you have a field called name, then name is a valid formula.
  • You only want to show a section on rows where age is greater than 65. In the container settings, under Show if... formula, enter age>65

Your formula must be an expression, not a statement. There should not be any multi line statements separated by semicolons. For this reason, you cannot use if(...) {...} In a formula, because this is a statement, not in the expression in JavaScript. Instead, for conditional expressions you should use the ternary operator :? . As and example, if you want to display a string "ELIGIBLE" based on age>65 and "NOT ELIGIBLE" otherwise, you can use this formula: age>65 ? "ELIGIBLE" : "NOT ELIGIBLE".

Any field in the current table, that is the table that the current view is based on, is available as a variable. You can also access join fields using dot notation. For instance, if the current table has a key field called author to the writers table, and the writers table has fields name and age, you can use the expression author.name in a formula

Where formulas in select field views and aggregations are very limited in the types of expressions they support, because they need to be checked for security and then translated to SQL. You can only use simple expressions such as name==="Foo" combined with &&, ||,  !, <, >, <=. You can also state that two fields should be equal such as name===name2.

Formulas are not passed directly to the database and are not subject to similar restrictions. There any valid JavaScript expression is a valid formula, provided that the variables used are in scope