Regulations, guidance and user journeys
Legislation in the form of Acts of parliament and regulations need to be interpreted by courts, tribunals, industry and citizens alike. Despite a move to plain language in drafting, the rules underpinning the legislation can be difficult to interpret and understand for all concerned, especially when the rules may be based on context or deeply nested.
Government agencies can help comprehension through the release of guidance material which aims to lead users through the legislation, focusing on prerequisites, definitions and other common issues. Even with this help, the rules can still be difficult to understand.
In situations such as this, web interfaces can be of help as they can be used to:
- Ask users the right questions depending on circumstances.
- Provide explanations on difficult to understand matters.
- Collect data which can help with decisions and outcomes.
- Present summary results personalised to the user.
GovCMS SaaS, as a platform, provides the necessary tool to deliver on complex flows, apply custom logic and present personalised results. This article provides practical advice for site owners and builders as to how a solution can be put in place using only the tools available on GovCMS.
Recipe ingredients
Webform
The venerable Webform module in Drupal can (almost) do it all. It provides a very flexible way of collecting user data with a variety of types and widgets. The user interface is also quite flexible, supporting steps, conditional fields and a final review stage before form submission. It is possible to build very demanding interfaces that are capable of collecting data for a wide variety of use cases. Webform is not the silver bullet for situations where the form needs to be particularly adaptive to user responses; however, in the majority of cases, it should be adequate.
Webform collects data and stores it in a keyed array. The data structure it builds is based are the view names, which have been configured and the values filled in by the user. The Webform values comprise the inputs used to build the results via the business rules.
Webform is available in GovCMS SaaS.
Submission preprocessor
The user's path through a Webform is dependent on how it has been set up.
- Forms can be a simple single page or can comprise several steps. Webforms with steps are helpful for complex flows that include several compartmentalised stages.
- Forms can include a “Review” step or can go straight through to the “Submit” stage. It is also possible not to provide a final submit button to the user so that a user can be restricted to just the Review stage. In some cases, such as presenting the results of business logic, just showing the Review stage is enough to provide the user with the results they need.
The Webform submission preprocessor can be customised to show the custom output on the Review screen. This submission handler can be thought of as a Controller. The Webform submission is the input to the calculation, which produces results (Model). The results can then be passed to a template (View) to display the answer.
The outcome for the user is that business rules have been applied to the form they have submitted to receive a personalised answer.
Calculation function
The calculation function converts the webform inputs into results. This is where the business rules are applied. This function is just a PHP function that can exist in the Drupal theme layer. There is no need for an external server or anything more complex than a simple function.
Care should be taken with managing the interface for the function. The simplest definition has it taking an associative array of inputs and returning an associative array of results.
Twig template
Once the results have been generated, they can then be passed off to a Twig template in the normal manner. This allows the themer to customise the display and presentation as required.
Developer’s blueprint
Now that we have covered the basics of the approach, you can see how to put it together using a concrete example of a ‘BMI calculator’. This example was chosen because it has multiple inputs (mass and height) and multiple outputs (the index and a label). The template allows for a customised message to be displayed.
Here are the steps to get it working.
Define the calculation
Create a PHP function which defines how the calculation works. This function takes a keyed array of inputs and returns a keyed array of results. You are free to implement any business logic you like in this function. The programmer has as much freedom as needed to implement the logic. Rules can be expressed directly as code, which is well known and understood.
This function should be saved in its own file. You do not need to repeat yourself when needing the functionality in the submission handler and the view.
/custom/theme/mytheme/inc/bmi.inc
<?php
function _bmi($inputs): ?array {
$mass = intval($inputs['mass']);
$height = intval($inputs['height']);
if ($mass == 0 || $height == 0) {
return NULL;
}
$index = $mass / $height / $height * 10000;
if ($index < 18.5) {
$label = 'Underweight';
}
elseif ($index < 25) {
$label = 'Normal';
}
elseif ($index < 30) {
$label = 'Overweight';
}
else {
$label = 'Obese';
}
return ['index' => $index, 'label' => $label];
}
Create a webform
User data needs to be collected via a Webform. As mentioned, this can be simple or complex. In the example below, we are collecting the mass and height of the user.
There are a couple of nuances to getting it to work right.
- The “preview” for the form needed to be enabled, and the preview button text updated.
- The submit button needed to be hidden.
- Do not show the progress bar.
- Turn off saving the form submission.
- Do not implement an email handler.
The YAML for the form has been provided below. You can copy and paste this in or create the Webform manually.
mass:
'#type': number
'#title': Mass
'#required': true
'#step': 1
height:
'#type': number
'#title': Height
'#required': true
actions:
'#type': webform_actions
'#title': 'Submit button(s)'
'#submit_hide': true
'#update_hide': true
'#preview_next__label': "What's my BMI"
The following screenshot shows how some of this looks like in the UI.
Preprocess the submission data
The webform submission will need to be processed to include the calculated results. The general gist is that the webform data (mass and weight) is sent across to the BMI function. The render array is then updated with the results. These can then be used in the template.
/themes/custom/mytheme/mytheme.theme
function mytheme_preprocess_webform_submission_data(&$variables) {
$variables['webform_submission'] = $variables['elements']['#webform_submission'];
if ($variables['webform_submission'] instanceof WebformSubmissionInterface) {
$inputs = $variables['webform_submission']->getData();
$variables['bmi'] = _bmi($inputs);
}
}
Twig template to handle the BMI results
The Webform module allows for the preview page to be templated. This allows us to make use of the BMI results which have been preprocessed.
/mytheme/templates/webform/webform-submission-data--bmi--preview.html.twig
{% set classes = [
'webform-submission-data',
'webform-submission-data--webform-' ~ webform.id()|clean_class,
view_mode ? 'webform-submission-data--view-mode-' ~ view_mode|clean_class,
] %}
<div{{ attributes.addClass(classes) }}>
{% if bmi %}
Your BMI is {{ bmi.index|number_format(1, '.', ',') }} making you {{ bmi.label }} and fabulous.
{% else %}
We were unable to calculate your BMI.
{% endif %}
</div>
That’s it. Job done. The results will now be displayed nicely to the user.
Create a view to show the results
One final thing you may wish to provide is an endpoint for other applications to also get results. It is possible to define a View (Page, JSON) which can take the inputs and then return the results with JSON. This can be achieved with a processor on the rendered results.
For our example, we did the following
- Create a BMI (bmi) view at /bmi
- The view should be a JSON Serialisation
- The view is not fetching data from Drupal and so can be on Content where nid = 0
- Add contextual parameters for mass and weight.
Our View looks like this in the UI.
View post render handler
The view will return nothing in its original state. We need to change that. Implementing a post render hook allows us to make the required adjustments.. You just need to make sure that the output is in the JSON format.
function mytheme_views_post_render(ViewExecutable &$view, &$output) {
if ($view->id() === 'bmi') {
$height = $view->args[1];
$mass = $view->args[0];
$results = _bmi(['mass' => $mass, 'height' => $height]);
$output['#markup'] = new string_to_markup(json_encode($results));
}
}
Now that this View is in place, external applications can make use of the endpoint to get the results they require, making Drupal a central location for the management and delivery of the logic.
How does this compare to Rules as Code (RaC)?
Rules as Code refers to a movement that seeks to shift the standard practices of governments so that they codify legislation into business rules, which can then be processed in a consistent way. This provides transparency and predictability. The rules can be leveraged to provide answers as to how the legislation would apply in certain circumstances.
The OECD has produced a “Cracking the code” report which explores the concept in some detail.
Rules as Code (RaC) is an exciting concept that rethinks one of the core functions of governments: rulemaking. It proposes that governments create an official version of rules (e.g. laws and regulations) in a machine-consumable form, which allows rules to be understood and processed by computer systems in a consistent way.
https://www.oecd.org/en/publications/cracking-the-code_3afe6ba5-en.html
In Australia, RaC has been made available on the GovCMS platform. https://www.govcms.gov.au/news-events/news/govcms-announces-enterprise-adoption-rules-code The system is currently in a trial phase with proof of concepts being delivered.
The RaC solution works as follows:
- The Drupal Webform module is used to collect data from users.
- The submission payload is then sent to a remote server hosting OpenFisca https://openfisca.org/en/ ,
- Rules (Python code) are stored in a code repository and are applied to the payload provided.
- The result is then returned back to the Drupal instance where it is added to the Webform data.
- Results can be displayed by templating the submission data.
The main differences between using RaC and the solution provided here are as follows:
- Location of logic: The RaC solution sends the payload to a remote server hosted outside the GovCMS platform. The pure Webform solution relies on PHP code located on the website.
- Programming language: The OpenFisca rules are codified in Python, rather than PHP as on GovCMS.
- Access: The RaC OpenFisca server would potentially have stronger access control around the endpoint, potentially limiting access to authenticated users only. The Drupal solution relies on the Views module for providing the endpoint.
It is worth noting the very close similarities between the two approaches:
- Transparency of rules: In both cases the actual definitions for the rules are located in code. The OpenFisca rules are located in a code repository and this could potentially be made public.
- Webform for the interface: The Webform module is used to collect data in both cases. The interface shown to the user will therefore be the same.
- Computer code: Rules are codified using computer code in a function or method. A number of different approaches have been taken to codifying the rules. In the two approaches showcased here code is operating on a data structure to return a result.
- Rendering: In both approaches the results are templated back in Drupal using Twig.
- API: There is an endpoint for potential use by other applications.
The above comparison shows that there are a lot of similarities in the techniques adopted by the two approaches. The native approach for GovCMS SaaS has the advantage of being readily implementable using the tools built into GovCMS. The OpenFisca approach has advantages around stronger access to the rules engine.
Conclusion
Getting the most from GovCMS SaaS is all about knowing how to work with the available tools. This article has shown a way for GovCMS developers to implement calculators and other decision-making tools using the modules available on the platform. Leveraging the Webform module (for the UI), a preprocessor (for the calculation) and templates (for the display) is a simple but powerful way to achieve the desired aim. The addition of a custom view provides a straightforward, but slightly obtuse, method for exposing the calculation via an endpoint with querystring parameters.
It is hoped that this article will open the way for the ready implementation of calculators on GovCMS sites, thereby helping citizens and industry navigate what might otherwise be impenetrable rules.