HTML

Article • 02.08.2022 • 11 minute(s) to read

HTML

HTML allows you to use HTML and JavaScript directly to create your Form Control. Hence, the HTML fills the gab between existing Form Controls, like Texts and Buttons, and the Custom Form Controls. HTML should be used when the desired functionality cannot be realized with existing Form Controls but you do not need the full range of capabilities of the Custom Form Controls.

The configuration of the HTML Form Control is done by clicking on Edit html and entering HTML and JavaScript code. HTML supports jQuery to implement the JavaScipt code.

JavaScript Example

This example calculates the sum of two entered numbers. Obviously, this can be done without HTML and purely with Form Controls, but this simply example shows the logic to work with HTML and JavaScript. This logic can then be applied to more complex problems.

The example makes use of two number Form Controls with the id/name Integer and Decimal as well es one Text Form Control with the id/name String. The Form needs to have those, so that this HTML can work. The id/name must be equal to the Id / Name property of the Form Controls the HTML should interact with. This implies that it is also possible to use MyVariable.Integer in the HTML, if the Form Control in question is linked to an Attribute of a Variable different to the Variable backing the current From.

<!-- Create a simple div element -->
<div id="output-div">Change the numbers.</div>

<!-- The logic is packed into the script here -->
<script>
    // Register listeners calling the function doUpdate() when a value in the Number Form Controls changes
    $(document).on('change', '[name="Integer"]', function(event) {
        doUpdate();
    });
    $(document).on('change', '[name="Decimal"]', function(event) {
        doUpdate();
    });

    function doUpdate() {
        // Read in the current values and convert them to integer or float
        var integerInput = parseInt( $('[name="Integer"]').val() );
        var decimalInput = parseFloat( $('[name="Decimal"]').val() );
        
        // Set the text of the div created above
        $('#output-div').text( 'Sum: ' + (integerInput + decimalInput) );
        
        // Set the text of a Text Form Control on the same Form as this HTML Form Control
        $('[name="String"]').val( 'Numbers are ' + integerInput + ' & ' + decimalInput );
        // Calling change() is needed so that the changes are applied to the Form Control
        $('[name="String"]').change();
    }
</script>
JavaScript access to Variables, Subscription Setting and Start Parameters

Variables and Start Parameters can be accessed from JavaScript by the so called context of a Form Control. It does not matter if the Form Control is linked to the Variables in question or not, since the Form Control is merely a gateway to access to any Variables and Start Parameters in the context of the current Instance.

The example below creates a button and links the press of this button to the call the function buttonClicked(). In this function buttonClicked(), Variables and Start Parameters are read and the results are put into another Text Form Control. This example requires the two Form Controls FormControl and OutputText on the same Form it is also on. While the type of FormControl can be a Text, Number, etc., the type of OutputText has to be Text. Obviously, also OutputText can be used instead of FormControl to access the Variables and Start Parameters via its context.

The function getFormControlData(formControlName) provides the necessary functionality to look up the context of an Instance by the name of a Form Control.

Be aware that it is not possible to set the value of Variables the same way as they are read in the example below. Therefore, If you what to output data from JavaScript, you can only do this by writing it into a Form Control. The Form Control can then be linked to a Variable to write the data into it. The Form Control can be hidden, so that the Users are unaware of this writing mechanism.

<!-- Create a button and link it to a function -->
<button type="button" onClick="buttonClicked()">Click me!</button>

<script>
    function buttonClicked() {
        // Get the context of a Form Control. This is required to access 
        // Context Variables, Entity Variables and Start Parameters
        var data = getFormControlData('FormControl');
        
        // Get the data in the Form Control itself
        var formControlValue = data.value()();
       
        // Get the value of Context Variable if the Context Variable has no
        // Attributes but only one single value
        var contextVariable = data.getContextValue('MyContextVariable')[0].Value;
        
        // Get an Attribute of a Context Variable
        var entityVariableAttribute = data.getContextValue('MyContextAttributeVariable')
                    .find( ({ FieldName }) => FieldName === 'AttributeName' ).Value;

        // Get a complete Entity Variable
        var entityVariable = data.getContextValue('MyEntityVariable');

        // Get an Attribute of a Entity Variable
        var entityVariableAttribute = data.getContextValue('MyEntityVariable')
                    .find( ({ FieldName }) => FieldName === 'AttributeName' ).Value;
        
        var startParameter = data.getContextValue('MyStartParameter')[0].Value;
        
        // Set the text of a Text Form Control on the same Form as this HTML Form Control
        $('[name="OutputText"]').val( formControlValue + contextVariable 
                                      + entityVariableAttribute + startParameter );
        // Calling change() is needed so that the changes are applied to the Form Control
        $('[name="OutputText"]').change();
    }
    
    // Helper function needed to access the context via Context Variables, 
    // Entity Variables and Start Parameters via Form Control
    function getFormControlData(formControlName) {
        var result;
        var controls = $('.aux-view-item');
        
        controls.each(function(index) {
            var data = ko.contextFor(this)['$data'];
            
            if (data.Name() == formControlName) {
                result = data;
            }
        });
        
        return result;
    }
</script>
JavaScript access to Switch Form Controls

The Switch Form Control can be accessed from JavaScript via the function described in the following example.

The example below creates a button and hides it based on the value of a Switch field in the process context. This example requires the Switch Form Control HideButton, which has to be one the same form. The Switch field has to have the values True and False.

The function getControlData(controlName) provides the necessary functionality to look up the context of an Instance by the name of a Form Control.

<!-- Create a button -->
<button type="button" id="myButton">Hide me!</button>

<script>
    // Helper function that is needed to access the values of the Form Controls
    function getControlData(controlName) {
        var result;
        var controls = $('.aux-view-item');
        
        controls.each(function(index) {
            var data = ko.contextFor(this)['$data'];
            
            if (data.Name() == controlName) {
                result = data;
            }
        });
        
        controls = $('.n-column');
        controls.each(function(index) {
            var data = ko.contextFor(this)['$data'];
            
            if (data.Name && data.Name() == controlName) {
                result = data;
            }
        });

        return result;
    }

    // Function to hide the button based on the new value of the Switch field
    function hideButton(newValue)
    {      
        if (newValue == 'true' || newValue == 'True' ){
            document.getElementById('myButton').style.visibility='hidden';
        }
        else{
            document.getElementById('myButton').style.visibility='visible';
        }
    }
    
    // Function that is executed as soon as the DOM has finished loading
    $(function() {
        // Set the variable for a Form Control you would like to get the data from
        var hideButtonValue = getControlData('HideButton');

        // Use .value().subscribe() on the variable to subscribe to any changes in the value
        hideButtonValue.value().subscribe(function(newValue) {
            // This code will be executed for each change in the value
            hideButton(newValue);
        })
    });
</script>
JavaScript Functions

The usage of jQuery is supported in the in your JavaScript and HTML code. Furthermore, additional JavaScript Functions are available to interact with Novunex Platform specific functionality. These functions are available by calling aurora.functionName(...), where functionName can be one of these functions:

  • apiUrl() - Returns the base URL of the core API

  • clientBaseUrl() - Returns the base URL of the current Account

  • createGuid() - Generates a unique identifier in GUID format

  • debounce( func, wait, immediate ) - Delays the call of the function func by the waiting time specified in wait. wait is interpreted as milliseconds. The wait is only executed if immediate is set to false. If immediate is set to true, func is called immediately.

  • forceLogout() - Forces an logout from the current user session

  • getAccessToken() - Returns the current access token of the authenticated User

  • getApiSubscriptionKey() - Returns the API Subscription key

  • getExistingParamsFromUrl() - Returns all Dashboard Parameters as an array. Each element in the array is an object in the form of { "Name": "ParameterName", "Value": "ParameterValue" }.

  • getFromCache( name ) - Retrieves the value stored in the local cache under the key name. All values are returned as string.

  • getSubscriptionId() - Returns the current Subscription ID

  • hexToRgb( hex ) - Converts the hex color string in hex to a RGB color string, e.g. “03F” to “0033FF”

  • htmlEncode( val ) - Encodes the string val to be in the HTML format, e.g., replacing &#60;, &gt; characters.

  • parseExpression( expressionString, contextIndex ) - Replaces variable names in the expressionString with their value. expressionString has to be a valid Form Control Expression and the variables have to be defined in the current context. contextIndex is deprecated and can be left null.

  • pushToCache( name, value ) - Stores value in the local cache under the key name

  • slugify( text ) - Generates URL slugs, i.e, replaces white spaces within - characters, removes all non-word characters, replaces multiple - with single - characters and trims start and end of string from any white spaces

  • tryParseJson( jsonString ) - Parses jsonString into a JavaScript Object. If the parsing fails, false is returned.

  • showApiError(...) - Generates an error popup and is used used in to handle the failure of the ajax(...) and the upload(...) function. See the documentation of the upload(...) function for an example usage.

  • ajax( settings ) - Executes a core service API call by calling the jQuery.ajax() function of the jQuery framework. settings is passed to the jQuery function. See the documentation of the upload(...) function for an example usage.

  • upload( type, url, data ) - Starts a file upload request, that has to be done in two steps:

    • The file content is uploaded first by calling upload( type, url, data ), where type specifies the HTTP method, url specifies the target of the request and data holds the actual data. The data has to be encoded as multipart/form-data and can hold the content of one or more files, but all files combines must be below the limit of 512MB. To keep the code responsive, it is advised to limit the number of files uploaded each time. upload(...) uploads the file content, creates the file in the file storage of the Novunex Platform and then returns the list of URIs to uniquely identify the newly created files on the Novunex Platform. The list of URIs is sorted in the same order as the list uploaded files.
    • The meta data is uploaded next by calling ajax(...). The meta data can also be uploaded as a list to handle multiple files at the same time, just like the file content before was. Obviously, this list need to be sorted in the same order. The following meta data entries are supported:
      • url - Mandatory entry that establishes the connection between the file content and its meta data. This must be set to the URI returned by upload(...).
      • name - Mandatory file name shown on the Novunex Platform for the uploaded file.
      • category - Optional categorization of the file. Either one of the predefined categories Documents, Images, Spreadsheets, Audio and Videos or a free text entry to define a custom category can be specified.
      • description - Optional free text describing the file.
      • size - Optional file size in bytes

    The example below shows to implementation of a function to upload multiple files at once by using the upload(...) and the ajax(...) functions. This example interacts with the other code the following way:

    • The files are expected to be uploaded by an file selector HTML element. Hence, somewhere on the page in input element of type file is required, like <input type="file" id="myfile" name="myfile">. Then, the example function can be called like
    uploadAll( Array.from( document.getElementById('myfile').files ) );
    
    • Similarly, once the files and the meta data are uploaded successfully, a map of the file names and the ID assigned by the Novunex Platform is composed. This map is then propagated to another function uploadComplete( finishedFiles ). Hence, this function needs to be implemented to handle the successful file upload.
    function uploadAll( inputFiles ) {
        // Prepare the file content as multipart/form-data
        var uploadContent = new FormData();
        inputFiles.forEach( function (file, index) {
            uploadContent.append('file-' + index, file, file.name);
        });
    
        // Upload the file content
        aurora.upload({
            type: 'post',
            url: aurora.apiUrl() + '/file/upload',
            data: uploadContent
        })
        .fail( aurora.showApiError )
        // When the file content has been uploaded successfully, the URIs are returned
        .done( function(uris) {
            // Compile the meta data of the files
            var uploadMetadata = { files: [] };
            inputFiles.forEach( function (file, index) {
                uploadMetadata.files.push({
                    // Mandatory: Link the meta data to the file content via the URL/URI
                    url: uris[index],
                    // Mandatory: Set the name of the file on the Novunex Platform
                    name: file.name,
                    // Optional category
                    category: 'Documents',
                    // Optional description
                    description: 'My file description string.',
                    // Optional file size in bytes
                    size: file.size
                });
            });
              
            // Upload the meta data
            aurora.ajax({
                type: 'put',
                url: aurora.apiUrl() + '/file',
                data: JSON.stringify( uploadMetadata )
            })
            .fail( aurora.showApiError )
            .done( function(fileIds) {
                const finishedFiles = new Map();
                fileIds.forEach( function( fileId, index ) {
                    finishedFiles.set( inputFiles[index].name, fileId );
                });
                // Inform the other components about the successful upload
                uploadComplete( finishedFiles );
            });
        });
    }
    
JavaScript User Information

The user objects offers information about the current User. This information can be accessed with aurora.user.propertyName, where propertyName can be one of the following properties:

  • id - The ID of the current User
  • username - The user name of the current User, i.e., this is the email address of the User
  • accessToken - OAuth access token of the User currently active in this session
  • refreshToken - OAuth refresh token of the current User needed to refresh the accessToken once it expires
  • subscriptionId - The unique ID of the subscription the current User is logged in
  • apiAccessKey - The subscription key for the subscriptionId
  • culture - The culture setting of the current User, e.g., en-US, de-DE, zh-CN, etc.
  • accountGuid - The globally unique ID of the current Account
Samples

Here you find code samples that are often required for HTMLs:

  • Load external JavaScript libraries - This examples loads JavaScript libraries that are not already provided by the Novunex Platform. All JavaScript libraries specified in the array scripts are loaded by this code. After executing this code in your HTML, you can use said JavaScript libraries.
$(function () {
    // Define the libraries to be loaded
    var scripts = [ "https://example.com/libs/mylib.js",
                    "https://domain.com/res/other.js" ];
    function loadScript(scripts) {
        // Iterate over all libraries
        var url = scripts.shift();
        $.getScript(url, function () {
            // As long as there are libraries, load them
            if (scripts.length > 0) {
                loadScript(scripts);
            // If there are no more libraries, call init() to use the libraries
            } else {
                init();
            }
        });
    }
}
In this article