Skip to content

DirectScript Usage Guide

Updated pdexter 2024-03-08

The DirectScript page can be used as a sandbox to test out ruleset script, or to run "batch processing" on documents. It is designed to test both clientside and serverside script.

This removes the need to create a template to work off, then a ruleset script attached to that template.

It can also be useful for demonstrating errors for submission to technical developers to debug an issue.

DirectScript Template ID

c22325e0-6283-11e6-b92d-278e9674be8b

Sample DirectScript page

Screenshot1

Running a client script

A client script is one that normally runs in response to OnLoad, OnFieldChange, or PreSave events. It acts in the browser javascript space, rather than the server nodejs space.

Script created here is executed as part of the document's OnFieldChange process (for the run button click).

To create a client script:

Syntax

runMe : [async] function(ntf, callback)

  • Create a function within the first parenthesis block ({}) called runMe
  {
      runMe : function(ntf, callback) {
        var main = this;
        var ft3 = ntf.scope;

        // insert script here
          ...

        callback(null, 'Run ok');
      }
  }
  • Add the script you want to run.

  • Click the button Run

Output/Debugging

The resulting logging will appear in the lower pane captioned Output Log. The process handling your script actually writes this logging to a document field called outputLog.

Most calls to ntf.logger will appear in this pane, so you can check the running of your script.

Alternatively, open a browser debugger console from your browser, to view output.

All calls to ntf.logger will appear in the console, so you can check the running of your script.

You can also present notications via ft3.showNotification and ft3.ModalService.showModal, or even the native alert function.

Debugging without output

As of DirectScript v202403A, ntf.logger.info/debug/error now accept a second argument, whether to output to the log pane, eg

ntf.logger.info('This goes both console and output');
ntf.logger.info('This goes only to console.', false);

This may be useful for large operations which might result in thousands of lines of logging, which can bog down the browser/page.

Running a server side script - preSaveServer

A server side script is one that occurs on the server, and is usually in response to a PreSaveServer, PostSave, a System Action or System Schedule.

Script created here is executed as part of the document's PreSaveServer process.

It will be necessary to save the DirectScript document, so you will need to set a Name, and optionally a Description.

To create a PreSaveServer server side script:

Syntax

preSaveServer : [async] function(ntf, callback)

  • Create a function within the first parenthesis block ({}) called preSaveServer
  {
      preSaveServer : function(ntf, callback) {
        var main = this;
        var ft3 = ntf.scope;

        // insert script here
          ...

      }
  }
  • Add the script you want to run.

  • Set the document's Name field (optionally, Group and Description).

  • Save the document

Output/Debugging

The resulting logging will appear in the lower pane captioned Output Log. The process handling your script actually writes this logging to a document field called outputLog.

All calls to ntf.logger will appear in this pane, so you can check the running of your script.

Because this runs on the server, you cannot raise UI notifications as for the client scripting.

Also see #Debugging_without_output

postSaveServer function

From DirectScript v202212B, it is possible to write a server side script to be performed post saving, in writing a function postSaveServer.

Syntax

postSaveServer : [async] function(ntf, callback)

This can be useful for long running processes that might exceed the http timeout of the browser, and the usual default timeout of the preSaveServer process. Timeout for any post save process is set to 10 minutes.

Logging under postSaveServer

Use of the ntf.logger object still writes output to the outputLog pane of the DirectScript.

An additional function is provided, ntf.logger.commit(), which will write the output log to the DirectScript document, so that a progressive output can be seen on the DirectScript.

To use the commit function, it is necessary to declare the postSaveServer function

Setting the Callback

Both client and server script requires a callback to be made at the end of its operation.

The callback function takes two arguments: errorMessage, and successMessage.

If the script is deemed to fail, you can simply call
callback('Something went wrong.').

If the script is deemed to complete successfully, call
callback(null, 'The operation was a success');

You must call callback in all paths of your script, otherwise the document may not save at all, and no output will be available.

Arm for Update

Available from DirectScript v202311A.

An extra "safety switch" can be deployed to prevent scripts containing data changing functionality from accidentally running and changing data.

Screenshot3

  • Add this line within the outermost brackets : requireArmForUpdate : true

  • Save -- when the above line is first set, than any data changing script will be inactive during save.

  • The Arm for Update checkbox will appear on the form, unchecked.

  • Whenever the script is run, either by Run button or by saving, any updating functions (updateDocument, createDocumentFromTemplate, deleteDocument) will be disabled, but will run as called.

  • To activate data changing functions, check Arm for Update, then click Run, or save the document (whichever is relevant).

Caveat : when Arm for Update is not checked, any of the above functions will run successfully, but not return a document object in their respective callback. Script will need to be modified to deal with these cases.

Script can utilise the document property chkUpdateFlag to check if the Arm for Update is checked.

runMe : function(ntf, callback) {  
    const main = this; 
    const armForUpdateFlag = ntf.document.chkUpdateFlag || !main.requireArmForUpdate ;
    ...

Listing

A listing of DirectScript documents should be available through the following listing document:

https://your-formbird-app/form/aca562c0-15a0-11e7-bcda-7bdc57bf9867

Samples

Client openDocument sample

{
    runMe : function(ntf, callback) {
        var main = this;
        var ft3 = ntf.scope;

        var tid = '07e7fbd0-cee3-11e5-aa08-fdabe14f1759';

        var newInfo = {
            commonName : 'Earwig',
            genus : 'Arghenis',
            species : 'Tonsuris'
        };

        ft3.openNewDocument(tid, newInfo, true, function(err) {
            ntf.logger.error(err);
            ntf.logger.info('OpenNewDocument done');

            callback(null, 'DirectScript run ok.');
        });

    }
}

Server updateDocument sample

{
    requireArmForUpdate : true, // for DirectScript v202311A & later

    runMe : function(ntf, callback) {
        var main = this;
        var ft3 = ntf.scope;

        // Enter code here

        callback(null, 'Run ok');
    },

    preSaveServer : function(ntf, callback) {
        var main = this;
        var ft3 = ntf.scope;
        ntf.userId = ntf.user.documentId; 

        var targetDocId = 'dad19f90-14d5-11e7-bcda-7bdc57bf9867';

        var change = {
            'description' : 'ererw-' + (new Date()).toISOString()
        };

        ft3.updateDocument(targetDocId, change, ntf.userId, function(err, doc) {
            if (err) {
                var msg = err.message.substr(0,160) + '...';
                callback('Error on update of asset = ' + msg);
            }
            else if (doc) {
                callback(null, 'Asset document updated with stuff');
            }
            else {
                callback('No error no doc');
            }
        } );

    }
}

Sample postSaveServer usage

Available from DirectScript v202212B

{
    postSaveServer : async function(ntf, callback) {
        var ft3 = ntf.scope;

        // Wait six seconds to output step 1
        await new Promise( (resolve, reject) => {
            setTimeout(function() {
                ntf.logger.info('postSaveServer Step 1 ...'); 
                resolve();
            }, 6000);
        });

        ntf.logger.info('Stage 1 complete');
        await ntf.logger.commit();

        // Wait six seconds to output step 2
        await new Promise( (resolve, reject) => {
            setTimeout(function() {
                ntf.logger.info('postSaveServer Step 2 ...'); 
                resolve();
            }, 6000);
        });

        ntf.logger.info('Stage 2 complete');
        await ntf.logger.commit();

        // Wait six seconds to output step 3
        await new Promise( (resolve, reject) => {
            setTimeout(function() {
                ntf.logger.info('postSaveServer Step 3 ...'); 
                resolve();
            }, 6000);
        });

        ntf.logger.info('Stage 3 complete');
        await ntf.logger.commit();

        callback(null, 'postSaveServer ok');
    } 
}