Monday 13 July 2015

JSLink with callback handler and synchronous ajax calls to validate user input.

Scenario:

For this specific case, I based myself on one of our client's requests, which was "to create some sort of validation, when a user submits an item in a booking list". 

There was a list indicating the stock of each item available for booking, so the approach was to request the number of items available (via ajax call) in the mentioned list and if that number was greater than "0", then the user should be able to make a booking.

Details:

Material field name : Material
Item availability list name : Item Availability
Booking list name: Material Bookings

Solution:

After the JSLink file being referenced in the list definition (Schema.xml), we can start developing our business logic.


  • Adding the callback handler to the new form.













  • In the "AddCallbackHandler" function we will have to:

    1. Get form context for current field
    2. Create a validator set to register the required validator and our custom validator
    3. Register our error callback
    4. Return the field default html (choice in this case) and a <span> tag which will contain our custom error message to be displayed when saving a new item is not allowed.
























  • Now let's define our custom validation
I developed a separate function to get the results, just because we needed to make more than one call. Note: "async" was set to false, otherwise it would have to be promisified.


  • To finish, we just have to define what happens when an error occurs.







Find the full code below:



Hope you find it useful ;)



No comments:

Post a Comment