Although many rules are already available by selecting them from the Data > Rules menu in the object inspector when a table or plot is selected, sometimes it can be useful to create a completely new rule from scratch.
Requirements
- An output that you wish to modify with a Rule.
- Comfort working with JavaScript code. See JavaScript Fundamentals if you're new to JavaScript or using it in Displayr.
Method - How to write your own rule
Step 1: Plan
The first step is to work out whether a Rule is appropriate for the task you want to perform. Ask yourself, is it possible to achieve this via a Rule or is there a better way? Is there already a similar script or example code that I can use or modify? If you are unsure of either of these, please contact Support at support@displayr.com.
When working out whether a custom Rule is appropriate, outline what you need to do. Some questions to consider:
- Is the Rule a one-off or something to be used again?
- How flexible does this Rule need to be?
- Is it for a specific table/statistic only or does it need to be applied to different table formats and/or statistics?
- Could a user potentially apply it to the wrong type of table?
- Is it meant for non-technical users?
- Would adding user input controls be helpful?
Example:
Let's look at an easy example of a Rule that shows only the top 5 rows (or fewer if less rows) of a table. In reality, this would only need the following code:
while(table.numberRows > 5) { table.deleteRow(table.numberRows - 1) }
-
table.numberRows
returns the number of rows in the table. -
table.deleteRow
deletes the last row of the table. Remember, JavaScript indices start at 0 so we need to minus 1. - This is placed within a
while
loop that stops once it reaches 5 rows.
But what if we want to allow the user to control the number of rows shown in the table? The below will take us through the various steps to consider when creating a custom rule using this example as a guide.
Step 2: Open the Edit JavaScript screen
1. Select your table.
2. Go to Data > Rules in the object inspector.
3. Click the Plus (+) button and select New custom rule (write your own JavaScript).
4. Click Edit JavaScript in the window that pops up and begin writing your rule.
Step 3: Add the relevant JavaScript library
If you intend to use functions from one of our online libraries then this needs to be referenced upfront using the includeWeb
function and the name of the library:
includeWeb("Table JavaScript Utility Functions");
See Table JavaScript Utility Functions for details on the various functions available for Rules. Note, the functions listed in Table JavaScript Reference are available without needing to reference an additional library. So we don't need this for our current example.
Step 4: Set headings and summary title
The heading is the text that will appear in the Rule form when you go to the Edit screen:
The summary title is the text that will appear in the Rules group in the object inspector:
These can be set as follows:
form.setHeading("Top 5 rows");
form.setSummary("Top 5 rows");
Sometimes you may wish to add the summary later in the code so it can be modified by input values.
In this example, we will set only the below heading upfront:
form.setHeading('Select the number of rows to show on a table');
Step 5: Add input controls
When a Rule is going to be used repeatedly and needs to be flexible, input controls can offer an easy way to allow the user to select the options they want to apply.
Options include:
- Numeric and text fields
- Combo and checkboxes
- Color pickers
In our example, we will create a user input to select the number of rows:
//Create the phrase 'Number of rows:'
var label_statistic = form.newLabel('Number of rows:');
//Create a control where a user can enter a number.
var numeric_up_down = form.newNumericUpDown('threshold');
// Specify the default number of rows to be shown
numeric_up_down.setDefault(5);
// Specify that the user must enter whole numbers.
numeric_up_down.setIncrement(1);
// Prevent the user from having tables with less than 1 row
numeric_up_down.setMinimum(1);
// Tell Displayr to create the form with the declared label and control
form.setInputControls([label_statistic, numeric_up_down]);
See How to Create User Input Fields in a Rule.
Step 6: Add table validations (optional)
Validations can be performed to check, among others, whether:
- The table data format is text instead of numeric.
- The table dimensions don't match the conditions of the Rule.
- The variable set structure of the input questions requires different code or is not appropriate.
- Previous Rules have modified the table or statistics.
See How to Add Table Validations to Rules.
Step 7: Declare your variables
Any chosen statistics, input field values, arrays, and objects need to be declared before writing the bulk of your code. This is also a good way to work out what you potentially will need to write in your code.
In our example, the key variable to declare is the input value to determine the number of rows to show. This then allows us to insert this value in the summary title:
// Extract the number of rows provided by the user and assign it to a variable.
var maximum_number_rows = numeric_up_down.getValue();
// Create the form title by referring to chosen value
form.setSummary('Top ' + maximum_number_rows + ' rows');
See JavaScript Fundamentals and How to Access Statistics from a Table in a Rule.
Step 8: Write your main script
The main part of your code should appear here. This often includes looping through the cells or labels in your table and modifying them in some way.
Here, we place the code that does the actual work of removing the rows we don't want:
// Delete the rows while(table.numberRows > maximum_number_rows) { table.deleteRow(table.numberRows - 1) }
See How to Work with JavaScript Arrays and Loops and How to Modify Table Rows and Columns Using a Rule.
See also How to Create a Custom Statistic or Calculation via a Rule and How to Modify Table Cells Using a Rule.
Step 9: Write any custom functions (optional)
Custom functions can help with simplifying the bulk of your code, especially when performed in multiple places. Functions can be added anywhere in the code, but for readability, it is often easier to place these at the bottom so the main part of the code is more accessible.
Step 10: Add a table footnote (optional)
When making modifications to a table, it can often be advantageous to add a footnote detailing these changes and/or any points of interest.
See How to Add a Custom Table Footnote.
Step 11: Check your code
- Press the Play button to check for code errors which, if any, will appear at the bottom of the screen in red.
- If there are no errors, press OK > OK and see if it has worked.
- If you don't get what you're after, go back to Data > Rules in the object inspector.
- Right-click the Rule you are working on > Edit > Edit JavaScript and re-check your code.
Here is the updated JavaScript in full:
includeWeb("Table JavaScript Utility Functions");
// Create the form
form.setHeading('Select the number of rows to show on a table');
//Create the phrase 'Number of rows:'
var label_statistic = form.newLabel('Number of rows:');
//Create a control where a user can enter a number.
var numeric_up_down = form.newNumericUpDown('threshold');
// Specify the default number of rows to be shown
numeric_up_down.setDefault(5);
// Specify that the user must enter whole numbers.
numeric_up_down.setIncrement(1);
// Prevent the user from having tables with less than 1 row
numeric_up_down.setMinimum(1);
// Tell Displayr to create the form with the declared label and control
form.setInputControls([label_statistic, numeric_up_down]);
var maximum_number_rows = numeric_up_down.getValue();
// Create the form title by referring to chosen value
form.setSummary('Top ' + maximum_number_rows + ' rows');
// Delete the rows
while(table.numberRows > maximum_number_rows) {
table.deleteRow(table.numberRows - 1)
}
Note that the comments explaining the code are shown in the code itself (i.e., Anything that follows a // is ignored by Displayr when it follows the instructions in the code). It is always a good idea to add lots of comments, as what seems obvious at the time you write the code can be hard for you and others to understand at a later time.
Re-applying the custom rule elsewhere
Once a Rule has been created, you can reapply it to other tables and charts in the same project using the Rules dialog via right-click > Apply.
To apply it to another project, you can:
- Repeat the steps described above, cutting and pasting the code from one project to another.
- Request that we add your rule to the Online Library so that it is available to all users.
- Create a QScript which adds the rule to a project, and then run this QScript using Anything > [Company Name] > Open QScript Editor. This is generally only worthwhile doing if there is a need for non-technical people to easily apply the rule to new projects. For instructions on how this is done, see How To Create a QScript To Insert a Custom Rule.
Common customizations
In some situations, a rule will have a set of options that you can easily modify, as follows:
- Go to Data > Rules in the object inspector.
- Right-click the rule that you wish to modify and select Edit.
Resources: Learning JavaScript
How to Work with Conditional JavaScript Formulas
How to Manipulate Strings Using JavaScript
How to Work with JavaScript Arrays and Loops
How to Use JavaScript in Displayr
How to Troubleshoot JavaScript Code in Displayr
Series: Learning How to Write Your Own Rules
1. How to Access Statistics from a Table in a Rule
2. How to Create a Custom Statistic or Calculation via a Rule
3. How to Modify Table Rows and Columns Using a Rule
4. How to Modify Table Cells Using a Rule
5. How to Create User Input Fields in a Rule
6. How to Add Table Validations to Rules
7. How to Reference and Calculate Tables in a Rule
8. How to Add Table Spans Using a Rule
9. How to Add a Custom Table Footnote