Field Validation Editable Grids

Scenario

Say I want to get the value of an editable grid cell on change and add some validation on it.
I have a field called ‘Contact Code’ and I want to be notified if I enter a value that is less than 4 characters.
field-validation-editable-grids
We need a way to reference the current field that was entered and validate its value.

getFormContext Method (Introduced in Dynamics 365)

The key is to pass the context object a parameter to the OnChange grid event and then use the getFormContext method to return the reference of the grid.
The handy thing about this is that it can return a reference to either a Form or Grid control depending on where it was called.
function EditableGridFieldValidation(executionContext) {

    var gridObject = executionContext.getFormContext().data.entity;
    var contactCodeValue = gridObject.attributes.getByName('new_contactcode').getValue();
    var contactCodeField = gridObject.attributes.getByName('new_contactcode').controls.getByIndex(0);

    if (contactCodeValue.length < 4) {

        contactCodeField.setNotification('Contact code cannot be less than 4 characters', 'ValidationAlert');
    }
    else {

        contactCodeField.clearNotification('ValidationAlert');
    }
}
Once you have created your code, you can upload your grid control (either on form, subgrid or homepage) by navigating to the Events tab.
Upload your script under Form Libraries like you normally do.
field-validation-editable-grids-3

Under Event Handlers, specify your Entity, Field and select ‘OnChange’ for the Event.
Effectively, you are going to call a function for the OnChange event that performs the field validation.
Click on Add to add your Jscript library and enter the name of the Function.
field-validation-editable-grids-4
Click on ‘Pass execution context as first parameter’ and hit OK. This will pass the executionContext object to the function.
field-validation-editable-grids-5

Publish your changes and you will see it in action !
So there it is, you can do basic string validation for editable grids using the new getFormContext method

Comments

Popular posts from this blog

Workflow Activity Input and Output Parameters and Data Types in MS CRM 2013/15/16

Get Workflow Guid in Javascript using OData query

Convert Plugin to Sandbox mode,