Klevr Product Documentation logo

Client Side Javascript

Along with the Client Side API, client-side access to Dynamics objects play an important role in customising your website.

Feature Overview

Along with the Client Side API, client-side access to Dynamics objects play an important role in customising your website. Customer Javascript files can be loaded to Dynamics form pages to greatly increase the possible functionality provided by the portal. As this will introduce code to portal and is not based on config, it is best to achieve functionality with OOTB abilities if possible. When required, Client Side Javascript is here to save the day!

Custom Validators

Validation is performed on change of fields as well as before submit. There is a global array called klevrValidators that is automatically defined on the page. This object is an array of objects consisting of a field and a func[tion] member. You can add new validators by adding items to this array. The func member must be a function that returns a string. The string should contain an error message to display to the user if the validation failed, otherwise it should return an empty string for successful validation.

Examples and Helpful Snippets

Here are some code examples for setting default values on a new form, as well as adding a custom validator. More details in the code comments.

//Example code for setting default values on a form.
//The site uses Vue, and a form vue app is referenced by the dFormApp variable. Fields are referenced by their schema names inside the $data member of the form app
//create a function to run once the window has loaded.
window.addEventListener('load', (event) => {
    //Check if we are on a create form by validating there's no id on the querystring
    //alternatively you could check if the field value itself is null
    if (window.location.search.replace("?", "&").indexOf("&id=") == -1) {
        //choices - array of ID's for picklist items
        KlevrForm.SetValue("klevr_choices", [3, 5]); 
        //choice - id of picklist item
        KlevrForm.SetValue("klevr_choice", 2); 
        // email, just like a string field
        KlevrForm.SetValue("klevr_email", "t@test.com");
        // string field
        KlevrForm.SetValue("klevr_name", "Test this stuff"); 
        // currency
        KlevrForm.SetValue("klevr_currency", 5.67);
        // decimal
        KlevrForm.SetValue("klevr_decimal", 7.89);
        // floating
        KlevrForm.SetValue("klevr_floating", 1.23);
        // date and time, standard JS date object
        KlevrForm.SetValue("klevr_independentdateandtime", new Date(2022, 4, 13, 13, 01, 05));
        // Date only, standard JS date object, time component ignored.
        KlevrForm.SetValue("klevr_independentdateonly", new Date(2022, 4, 13, 13, 01, 05));
        //multiline with \n for line breaks
        KlevrForm.SetValue("klevr_multiline", "test\nline2");
        // whole numbers (integers)
        KlevrForm.SetValue("klevr_wholenumber", 5);
         //boolean fields
        KlevrForm.SetValue("klevr_yesno", true);
        //Example of setting a lookup
        KlevrForm.SetValue("klevr_lookupid", {
            id: 'e7c7be59-e1cf-4d79-9466-323afb9ac3cd',
            name: 'Label in Lookupfield',
            entityname: 'klevr_entityschemaname'
        });
        //Or
        KlevrForm.SetLookupValue("klevr_lookupid", 'e7c7be59-e1cf-4d79-9466-323afb9ac3cd', 'Label in Lookupfield', 'klevr_entityschemaname');
        //Or if you are not changing the type, you can leave the entitytype off
        KlevrForm.SetLookupValue("klevr_lookupid", 'e7c7be59-e1cf-4d79-9466-323afb9ac3cd', 'Label in Lookupfield');
    }
});

//example of a custom validator. klevrValidators is a global array consisting of objects with members for field and func[tion].
//functions are passed the value of the field when they are called. Type dependent on field type.
//Functions should return an error message to display to the user, or a blank string if validation passes.
//Other field values can be referenced through the dFormApp.$data object as above.
klevrValidators.push({
    field: "klevr_name", //reference field by its schema name.
    func: function (el) {
        if (el.length < 7) return "The title is still not descriptive enough.";
        else return "";
    }
});

Get URL ID

// get id from the current record
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    var results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}
 
// Store the string value of the id in a variable that can then be used to redirect or make API calls
var idVariable = getUrlParameter("id").toString();

Store the ID from a lookup field on the form value in a variable

// get the product ID 
var productId = KlevrForm.GetValue("ws_product").id;

Use klevr Validators to do front end validation

klevrValidators.push({
    field: "ws_quantity",
    func: function (el) {
        if (el <= 0) return "Quantity can not be a negative or 0. Please enter a positive number.";
        else return "";
    }
});

Find the value of an answer within a klevr form (this function assumes there's only one klevr form on the page)

//this function takes the section title, question title and anwser index (0 for non-repeatable sections, or the index of the answer within a repeatable section)
GetDynamicsQuestionnaireAnswer = function(sectiontitle, questiontitle, answerIndex) {
  var FindProp = function(o, p) { for (let i in o) if (p(i, o[i])) return o[i]; };
  var myklevrform = FindProp(dFormApp.$refs, (r, v) => r.startsWith('dq'));
  if (!myklevrform) return null;
  var section = FindProp(myklevrform.$data.myquestionnaire.sections, (r, v) => v.sectiontitle==sectiontitle);
  if (!section) return null;
  var question = FindProp(section.fields, (r, v) => v.questiontitle==questiontitle);
  if (!question) return null;
  return question.answers[answerIndex].value;
}

File Upload interception

In order to trigger a custom function when the user selects a file for upload on the Blob attachment control, you can use the following code to capture the files as they are selected:

function myFileValidator(fl) {
    console.log(fl.name);
}

for(var i in dFormApp.$refs) {
    if (i.startsWith('fileupload')) { 
        var rf = dFormApp.$refs[i];
        Vue.watchEffect(() => { 
            for (var fl of rf.$data.files) myFileValidator(fl); 
        });
    }
}

Field Watchers

Often times an API call should be made to grab details of a record after it is selected in a lookup field on the form. The following code will "watch" the lookup field and will execute the code upon changes to the lookup field.

//update on change of value in lookup field
KlevrForm.AddOnChange("yourLookupSchemaname e.g. klevr_customerid", (newvalue, oldvalue) => { console.log("lookup changed ! - Write your code in this function."); });

Show or hide a dynamics field

You can show and hide dynamics fields by calling Show, Hide or ToggleVisible methods of KlevrForm object.

Syntax:

  • KlevrForm.Hide('<FieldName>');
  • KlevrForm.Show('<FieldName>');
  • KlevrForm.ToggleVisible('<FieldName>', <true/false>);

Replace

  • <FieldName> with the actual field name. e.g. klevr_name
  • <true/false> with true to show and false to hide
//hide the field klevr_name
KlevrForm.Hide('klevr_name');
//alternatively, you can do the below as well
KlevrForm.ToggleVisible('klevr_name', false);

//shows the field klevr_name
KlevrForm.Show('klevr_name');
//alternatively, you can do the below as well
KlevrForm.ToggleVisible('klevr_name', true);

Required (mandatory) / optional a dynamics field

  • You can make a field required/mandatory and optional using Required, Optional, ToggleRequired methods of KlevrForm object.

Syntax:

  • KlevrForm.Required('<FieldName>')
  • KlevrForm.Optional('<FieldName>')
  • KlevrForm.ToggleRequired('<FieldName>', <true/false>)

Replace

  • <FieldName> with the actual field name. e.g. klevr_name
  • <true/false> with true to lock and false to unlock
//Make the field klevr_name required
KlevrForm.Required('klevr_name');
//alternatively, you can do the below as well
KlevrForm.ToggleRequired('klevr_name', true);

//Make the field klevr_name optional
KlevrForm.Optional('klevr_name');
//alternatively, you can do the below as well
KlevrForm.ToggleRequired('klevr_name', false);

Lock (read-only) / unlock (read-write) a dynamics field

You can lock and unlock a field using Lock, Unlock, ToggleReadOnly methods of KlevrForm object.

Syntax:

  • KlevrForm.Lock('<FieldName>')
  • KlevrForm.Unlock('<FieldName>')
  • KlevrForm.ToggleReadOnly('<FieldName>', <true/false>)

Replace

  • <FieldName> with the actual field name. e.g. klevr_name
  • <true/false> with true to lock and false to unlock

When you lock or make a field readonly, if the field is marked as mandatory/required, it will be marked as optional. This is to removed the '- readonly' next to the field label for better user experience and less code in your javascript. In case you want to make the field mandatory on switching from locked/readonly to unlocked/read-write, please call the KlevrForm.ToggleRequired or KlevrForm.Required method.

//lock the field klevr_name
KlevrForm.Lock('klevr_name');
//alternatively, you can do the below as well
KlevrForm.ToggleReadOnly('klevr_name', true);

//unlock the field klevr_name
KlevrForm.Unlock('klevr_name');
//alternatively, you can do the below as well
KlevrForm.ToggleReadOnly('klevr_name', false);

Get or set a dynamics field value

You can get and set field values using GetValue and SetValue methods of KlevrForm object.

Syntax:

  • To get a field value
    • KlevrForm.GetValue('<FieldName>');
  • To set a field value
    • KlevrForm.SetValue('<FieldName>', '<Value>'); //For string value fields
    • KlevrForm.SetValue('<FieldName>', <Value>); //For numeric & boolean value fields
    • KlevrForm.SetValue('<FieldName>', [<Value>]); //For multiple value fields (example:. multi-select dropdown field)
    • KlevrForm.SetLookupValue('<FieldName>', '<ID>', '<Name>', <EntityType>); //For lookup fields. Note - EntityType is optional if it has not changed

Replace

  • <FieldName> with the actual field name. e.g. klevr_name
  • <Value> with the actual value to set to that field. e.g. 'Bob'
  • <ID> with the id of the field value
  • <Name> with the name you want to display on screen for this field. Please note
    • This will not be updated in the database on form submit as the id field value is used as a source to associate the resource.
    • Also, if the lookup field is marked rendered as dropdown in read-write mode in Umbraco, the name value will have no effect on your UI as it will automatically take the associated name for the submitted ID
  • <EntityType> with the entity type. This is an optional field which is required only when the entity type changes.
//gets the value of the field klevr_name
KlevrForm.GetValue('klevr_name');

//sets the value of the string field klevr_name to 'Bob'
KlevrForm.SetValue('klevr_name', 'Bob');
//sets the value of a numeric field klevr_decimal to 2.1
KlevrForm.SetValue('klevr_decimal', 2.1)
//sets the value of a boolean field klevr_yesno to true
KlevrForm.SetValue('klevr_yesno', true)
//sets the value of a dropdown field klevr_choices to ID  1
KlevrForm.SetValue('statuscode', 1)
//sets the value of multi-select dropdown field klevr_choices to ID's 1 & 2
KlevrForm.SetValue('klevr_choices', [1,2]); 
//Set a lookup field value
KlevrForm.SetLookupValue('klevr_lookup', 'd6f0948d-f5d9-eb11-bacb-00224815864e', 'Switzerland', 'klevr_country'); //Specifying entitytype is optional if it doesn't change
//sets the value of Rich text editor field
KlevrForm.SetValue('klevr_rtf', '<blockquote>abcd</blockquote><ol><li data-list="ordered">1</li><li data-list="ordered">2</li></ol>');

Add watcher for a dynamics field

You can add watchers to a field to perform an action when a field value changes using AddOnChange method of KlevrForm object. An example usage of this function is to show/hide a field based on the value change of another field (like when a drop-down field value changes).

Syntax:

  • KlevrForm.AddOnChange('<FieldName>', <Function>)

Replace

  • <FieldName> with the actual field name. e.g. klevr_name
  • <Function> with a function with two parameters where the first parameter will have new value (value of the field after update) and the second will have old value (value of the field before update). You can have your logic written inside the function which will execute when the field value changes.
KlevrForm.AddOnChange('klevr_dropdown', 
  (newValue, oldValue) => { 
  //show klevr_email if klevr_dropdown's new value is 3, otherwise hide klevr email
      KlevrForm.ToggleVisible('klevr_email', newValue == 3); 
});

Show and hide a dynamics section

You can show and hide a dynamics section using HideSection, ShowSection, ToggleSectionVisible methods of KlevrForm object.

Syntax:

  • KlevrForm.HideSection('<SectionName>')
  • KlevrForm.ShowSection('<SectionName>')
  • KlevrForm.ToggleSectionVisible('<SectionName>', <true/false>)

Replace

  • <SectionName> with the actual section name set in the Umbraco for that section but in all lower case. e.g. If the section name is 'General' in Umbraco, enter 'general' as the value for this
  • <true/false> with true to show and false to hide
//hide a dynamics section with the name 'general'
KlevrForm.HideSection('general');
//alternatively, you can do the below as well
KlevrForm.ToggleSectionVisible('general', false);

//show a dynamics section with the name 'general'
KlevrForm.ShowSection('general');
//alternatively, you can do the below as well
KlevrForm.ToggleSectionVisible('general', true);

Show and hide a comments section

You can show and hide a comments section using ShowComments, HideComments methods of KlevrForm object.

Syntax:

  • KlevrForm.ShowComments('<CommentSectionName>')
  • KlevrForm.HideComments('<CommentSectionName>')
//show a comment section with the name 'portalcomment'
KlevrForm.ShowComments('portalcomment')

//hide a comment section with the name 'portalcomment'
KlevrForm.HideComments('portalcomment')

Avoid marking a field as dirty on value change

Whenever a data field is changed after the page loads, the field is marked as dirty and there will be a warning pop-up to let the user know that there will be a data loss if the user tries to navigate away from the current page without submitting (saving) the form. If you want to avoid this for any field, you need to hide or lock the field before changing its value.

Setting the options for a Money Field

If you are using the new donation style money field, you can dymacially change the preset options displayed to the user. To do this, you can use the KlevrForm.SetMoneyPresets function.

Syntax:

  • KlevrForm.SetMoneyPresets('<FieldName>', '<comma separated values>');

Replace:

  • <FieldName> with the schame name of the field associated to the money control
  • <comma separated values> with a list of values you want presented, e.g. '10,20,50,100,250'
KlevrForm.SetMoneyPresets('klevr_currency', '10,20,50,100,250');

Implementation

Add your custom code to a new .js file and upload it to the Umbraco back office as media. Hint, place it in a script folder to keep it nicely organised. Go to the page under content, and select the script in the "custom Script" parameter for the page. These files are stored within the 'media' container in the storage account that is deployed with the rest of the Klevr Portal resources.

Security Considerations

  1. Any interaction with dataverse from custom JS files will bypass the permissions that have been set u in the back office. Keep this in mind.
  2. Make sure that all required fields are added under their entity on the API config page.

Last updated on