Skip to content

Rules

A rule can be used to determine if a certain condition is fulfilled or not. To create a rule, use the Rule class from perseus.frontend_form like this:

from perseus.frontend_form import Rule
rule = Rule(
empty_fields=["SOME_ID", "ANOTHER_ID"],
filled_fields=["SOME_ID", "ANOTHER_ID"],
expressions=["{{some expression}}", "{{another expression}}"],
external="some://url.com",
)
  • empty_fields contains a list of strings, which are IDs of fields in the form. It returns to True if all of these fields are empty.
  • filled_fieles contains a list of strings, which are IDs of fields in the form. It returns to True if all of these fields are filled by the user.
  • expressions contains a list of strings, which are expressions as described here. It returns True if all those expressions are compiled to True.
  • external is a string which holds a URL. This endpoint will be called using GET, and it will receive the current status of the form as a list. If the endpoint in external returns True, it will also be considered True in the rule. Any other return value will be considered as False.

A rule is only considered as fulfilled if every aspect within the rule is True (AND operator).

Most of the time, you can pass a list of rules instead of just one. If this is the case, multiple rules are connected with the OR operator. Therefore, only one rule has to be fulfilled for the whole list to be considered as fulfilled. Empty rules are always fulfilled.

Sometimes you maybe want to hide or show certain parts of the form depending on the user input.

To achieve this, you can use the visibility parameter when creating a form item or update it later. You can check out both variants in the following example:

from perseus.frontend_form import CheckboxInput, FrontendForm, Rule, TextBlock
form = FrontendForm()
checkbox = CheckboxInput("CHECKBOX", "Check this if you want to")
text_checked = TextBlock(
content="Show if checkbox is checked",
visibility=[Rule(expressions=["{{ equals([CHECKBOX], true) }}"])]
)
text_not_checked = TextBlock(
content="Show if checkbox is **not** checked"
)
text_not_checked.visibility = [Rule(expressions=["{{ equals([CHECKBOX], false) }}"])]
form.add_items(checkbox, text_checked, text_not_checked)

The visibility is defined as a list of Rule objects. This list represents an OR relationship, so the element will be visible if at least one rule is fulfilled.