Tag Archives: JSLink

JSLink and Display Templates Part 5 – Creating custom List Views

This post will look at a slightly different scenario – List Views. The general principles are the same (we write some JavaScript which tells SharePoint to override the rendering of various elements) but because we are now dealing with a whole view instead of just a single field there are some new elements to play with.

This is actually one of the more simple examples so I’ll start with all of the JavaScript in one block

var mjhViews = mjhViews || {};

mjhViews.itemHtml = function (ctx) {
  var returnHtml = “<h2>” + ctx.CurrentItem.Title + “</h2>”;

  if (ctx.CurrentItem.MyCustomField) {
    returnHtml += “<p>” + ctx.CurrentItem.MyCustomField + “</p>”;
  } 
  return returnHtml;
};

(function () {
  var mjhOverrides = {};
  mjhOverrides.Templates = {};

  mjhOverrides.Templates.Header = “<div id=’MyCustomView’>”;
  mjhOverrides.Templates.Item = mjhViews.itemHtml;
  mjhOverrides.Templates.Footer = “</div>”;
 
  mjhOverrides.ListTemplateType = 104;
  mjhOverrides.BaseViewID = 1;
 
  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(mjhOverrides);
})();


So we start off as good JavaScript developers and create ourselves a namespace (mjhViews) for our function (so we don’t pollute the global namespace). This contains a single function (mjhViews.itemHtml) which accepts the same render context object we’ve been using throughout this series.

The itemHtml method simply returns some basic HTML consisting of the item Title in an H2 element followed by the “MyCustomField” (if it exists, this field was used in Parts 3 and 4). Of course there are different methods for retrieving the values of the current item but the render context will automatically provide properties for the basic data types (some field types, external data fields in particular, don’t work like this and you might need to get creative with AJAX REST calls but be careful about performance!).

Finally we have our anonymous function which actually registers this override with SharePoint, and this is where things get interesting.

The main thing you might notice here is that we aren’t controlling any specific fields but instead override the “Header” and “Footer” with plain old HTML. For the “Item” we reference our rendering method and this will be executed for every item present in the view.

We then have two more properties (both of which are optional by the way).
The ListTemplateType and the BaseViewID both define which specific list types and views this rendering should be used for. If you don’t specify values for these then when this rendering override is registered it will override EVERY list and view on the page.

Finally we use the same old RegisterTemplateOverrides to tell SharePoint to process our object and do its thing!

Now before I apply this view it looks like this (which should be a pretty familiar SharePoint view):

Standard SharePoint list view

Once I apply my custom view rendering it looks like this:

A custom (if slightly boring) list view done with JavaScript

So .. quite easy huh? But the bright among you might have wondered .. where the hell has the toolbar and paging gone? Ahh .. yes .. that is all handled by the header and footer.

The header and footer contain important List View elements

This isn’t the only setback, if you try to use the view I defined above in “Quick Edit” mode then you also get the following error message:

TypeError: Unable to get property ‘style’ of undefined or null reference

The problem is that if you don’t override the Header you get some slightly funky behaviour because the headers injects a table object and it expects your content to be rendered inside that HTML table as rows. So by default I end up with the following (note the headers are at the bottom!)

Custom rendering with the header intact, but column headers are appearing AFTER the other content

So if you really want to play ball with the list views (and want the headers to be available) then you need to use TR and TD elements for your render HTML. For example:

mjhViews.itemHtml = function (ctx) {
  // start with a <tr> and a <td>
  var returnHtml = “<tr><td colspan=’3′>”;

  returnHtml += “<h2>” + ctx.CurrentItem.Title + “</h2>”;

  if (ctx.CurrentItem.MyCustomField) {
    returnHtml += “<p>” + ctx.CurrentItem.MyCustomField + “</p>”;
  }
  // close off our <td> and <tr> elements
  returnHtml += “</td></tr>”;
  return returnHtml;
};
Once we put this in place, our headers are back in the right place.

Custom rendering with column headers in the right place

Making your views use the correct Display Template
In order to make sure the Display Templates are used in the correct places you have a number of options.

  1. In your schema.xml of a custom list definition you can define the JSLink property allowing you to override specific views. This allows you to build List Templates which have completely bespoke views when required (especially useful for use with list view web parts)
  2. You can define the JSLink property on the List View Web Part .. and this works either for defined views in the List or for List View Web Parts which you have dropped onto other web part pages or publishing pages.
  3. You can use Code / PowerShell to modify the JSLink property of the SPView object programmatically
  4. You can of course just drop in your JavaScript file using a Script Editor or custom Master Page and use the ListTemplateType and BaseViewID properties I told you about at the beginning on this post 🙂
  5. or you can use a funky new method which allows users to create their own views using your custom templates … but more about that in Part 6 🙂

So that pretty much covers off how list views can be rendered using bespoke code. Hope you’ve been enjoying the series but we’re not done yet!

..

Next – Part 6 – Creating View Templates and Deployment Options

JSLink and Display Templates Part 4 – Validating user input

In the previous posts we have looked at JSLink and how we can use it, we have looked at overriding the rendering of individual fields both for display and also for editing. Now we are going to look at Validators and how we can validate user input before their changes are saved.

In order for a validator to work you need three moving parts:

  • Validation method (to tell SharePoint if the field input is valid or not)
  • OnError method (to handle any errors which are raised)
  • Registration code to do the plumbing

Validation Method
We’ll base this sample on the Custom Editing interface we built in Part 3 and first off we will build ourselves a validation method.

This is technically going to be an object with a Validate method (to which SharePoint will pass a value). The code for this method is as follows:

mjh.MyCustomFieldValidator = function () {
  mjh.MyCustomFieldValidator.prototype.Validate = function (value) {
    var isError = false;
    var errorMessage = “”;

    if (value == “Item 2”) {
      isError = true;
      errorMessage = “You cannot select ‘Item 2′”;
    }
    returnnew SPClientForms.ClientValidation.ValidationResult(isError, errorMessage);
  };
};

The code above contains a very simple if statement to check the items value (in my example saying that an error message will be displayed if the item value is set to “Item 2” .. one of the drop-down choices from Part 3 of this series).

Finally we call the SPClientForms.ClientValidation.ValidationResult method passing in our “isError” (a true/false boolean) and the error message (a text string).

OnError Method
We then need a final method which tells SharePoint basically what to do when an error actually occurs. This is a fairly simple method in which you can basically do whatever you want (pop-up alerts, add HTML to the page, change CSS, whatever you need).

Now we could just use an Alert(error.message) function if we wanted a particularly crude error message but it would be much better to have some formatted error message just like SharePoint does out of the box .. and for that to work we first need to have ourselves a recognisable element that we can manipulate using jQuery, so we add the following code to our rendering method for the edit interface:

// add the error span
returnHtml += “<span id=’MyCustomFieldError’ class=’ms-formvalidation ms-csrformvalidation’></span>”;

Once we have this we can manipulate it in our “onError” function (which as you can see is very simple).

mjh.onError = function (error) {
  $(“#MyCustomFieldError”)
  .html(“<span role=’alert’>” + error.errorMessage + “</span>”);
};

So all we are really doing is grabbing the span using the ID we gave it, then injecting our error message.

Now for the plumbing …
So the only thing missing is making this all hang together from inside our render method:
var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);

// register the field validators

var fieldValidators = new SPClientForms.ClientValidation.ValidatorSet();

if (formCtx.fieldSchema.Required) {
  fieldValidators.RegisterValidator(
    new SPClientForms.ClientValidation.RequiredValidator()
  );
} fieldValidators.RegisterValidator(new mjh.MyCustomFieldValidator());

formCtx.registerValidationErrorCallback(formCtx.fieldName, mjh.onError);
formCtx.registerClientValidator(formCtx.fieldName, fieldValidators);

So lets walk through what we are doing in the code above.

First off we create ourselves a new ValidatorSet which will contain the validators that we need for the field. We then do a simple check to see if it is a required (mandatory) field and if it is we add the standard SharePoing “RequiredValidator” to our ValidatorSet.

Then we add our own new “MyCustomFieldValidator” object to the validator set.

Finally we have two register methods. The first one registerValidationErrorCallback is basically telling SharePoint that if our field fails validation that it should call the mjh.onError method to deal will letting the user know what has gone wrong.

The second one registerClientValidator actually registers our validators with SharePoint for the chosen field.

Note – it is perfectly possible to register your client validator without providing a validation error callback. If you do this then the validator will stop the form from being saved but the user won’t be told why (they’ll just get a frustrating form which won’t post back).

So ..  assuming all of the above has worked correctly you would see something like this if you tried to selected “Item 2”:

Validation message being shown in SharePoint

So that should be what you need to start putting together your own custom validation. You can of course use this technique on any number of fields.

For the complete code-sample to date (including Parts 2 and 3) please download the Visual Studio solution here:

https://sdrv.ms/15eB6CI

….

Next – Part 5 – Creating Custom List Views

JSLink and Display Templates Part 3 – Creating a custom editing interface

So this part talks about some of the more interesting bits of Display Templates .. the editing interface. This introduces some new features as not only are we required to provide and rendering all of the editing controls but we also have to somehow get SharePoint to understand what value it should use when someone wants to save their changes.

Now the process for creating an editing interface is identical for both “New” and “Edit” forms (with the exception that the editing interface also needs to deal with loading up existing values) so for this post our examples will focus on the “Edit Form” functionality.

Registering our Edit Form function
So this uses exactly the same technique that we walked through in Part 2, where we register our desired override method for our named field.

(function() {
  var mjhOverrides = {};
  mjhOverrides.Templates = {};

  mjhOverrides.Templates.Fields = {  

    ‘MyCustomField’: {
      ‘NewForm’: mjh.editMethod,
      ‘EditForm’: mjh.editMethod
    }
  };

  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(mjhOverrides );
 })();
So just like before we create ourselves an override object and tell it we want to use the method “mjh.editMethod(ctx)” to render both the “EditForm” and “NewForm” for our field “MyCustomField” and we then register that using the SPClientTemplates.TemplateManager.RegisterTemplateOverrides method.

The Edit Render Method
The format of the rendering method for the edit interface (in this example) is pretty straightforward. I have simply rendered out a drop-down list containing three items.

mjh.editMethod = function (ctx) {
  var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx); 

  formCtx.registerGetValueCallback(formCtx.fieldName, mjh.getFieldValue.bind(null, formCtx.fieldName));

  // items to appear in the drop down list
  var items = new Array(“Item 1”, “Item 2”, “Item 3”);
  var returnHtml = “<div id=” + ctx.CurrentFieldSchema.Name + “><select>”;
 
  for (var i = 0; i < length; i++) {
    returnHtml += “<option”;
    if (ctx.CurrentFieldValue == items[i]) {
      // select the current item if the value matches
      returnHtml += ” selected “;
    }  
    returnHtml += “>” + items[i] + “</option>”;
  }

  returnHtml += “</select></div>”;
  return returnHtml;
};

 

Now as you can see this time we have a new method in play as we are also creating a new “FormContext” object and using the registerGetValueCallback method. This method is what tells SharePoint to use our method to find out what the field value should be when the item is saved. The first argument is the name of the field we are overriding, and the second argument is the method that will return our field value.

We have also made use of the JavaScript “bind” function so that we can specify arguments that should be passed to our callback method, in this case we want to pass the field name (you’ll see why in a minute). 

The only other thing special going on here is that I check to see if the current value of the item matches the option, and if it is we add the “selected” attributed.

We have also enclosed the whole thing in a div using the fieldname as the ID, which we can use in our callback method below …

The Get Value callback
The next thing of course is our method to retrieve the actual field value, and for this we use a little bit of jQuery (you can choose your own way of getting the jQuery library onto the page. Adding it as an extra JSLink URL is quite cool, although if you use jQuery everywhere you might otherwise want to use a Custom Action or Delegate Control so it appears on every page).

mjh.getFieldValue = function (fieldName) {
  // a div used with jQuery to identify the appropriate items 
  var divId = “#” + fieldName;
  // get the selected item 
  var selectedItem = $(divId + ‘ option:selected’)[0];
  // return the value 
  return selectedItem.innerText;
};
So you can see above that we are using the fieldName argument so we can identify the correct div. This allows us to use the same methods on multiple fields without them clashing.
We then simply use a small jQuery statement to pull out the selected item (the “option” element which has an attributed of “selected”) and return the “innerText” (which in our example is the value we want to save). Of course you need to be mindful of the data type of the field you are working with. All values are returned as Text but fields such as People and Lookup Fields need to return a specifically formatted string.
I then bound this to a site column (of type Text) with the following schema:
<Field ID={A424AE9E-1F1D-4ECE-B695-202F5106352E}
  Name=MyCustomField
  DisplayName=My Custom Field
  Description=a text field which has custom rendering?
  Type=Text
  Required=FALSE
  Group=MJH JSLink Columns
  JSLink=~layouts/MJH.JSLink/jquery-1.10.2.min.js|~layouts/MJH.JSLink/MJH.JSLink.js
  Overwrite=TRUE>
</Field>
Once that is all deployed it should look something like this …

My Custom Field – a Text field but rendered as a drop-down list

So that is pretty much all you need to get going with editing of fields. Come back for Part 7 where I share sample code for handling Lookup Fields (and converting them to checkbox lists), cascading dropdowns and generating values by calling AJAX REST queries.

In the meantime you can download the sample code from this example here:
https://sdrv.ms/14KtFgv

Next – Part 4 – Validating user input

JSLink and Display Templates Part 2 – Changing how individual fields display

This is part two in my JSLink and Display Template series, and in this post we will be looking at the actual Display Template JavaScript code to override the rendering of individual fields.

If you haven’t read Part 1 and then it is well worth a look, if nothing else you need to understand the URL tokens and where/how you use JSLink to get your Display Template in the right place.

So what will we be doing?
The premise of using Display Templates here is simple, we are going to tell SharePoint
that when it wants to render a field we want it to use one of our JavaScript functions instead of the “out of the box” one.

We can do this on each field for four different rendering methods:

  • Display Forms
  • Edit Forms
  • New Forms
  • Views (as in, list views)

This post will look at the “Display Form” while the others are covered in further posts in this series.

Registering your Override Methods
The magic all happens through a SharePoint JavaScript method called SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx). This expects a single object to be passed in which declares what exactly we want to override.

This method call is actually the same we use throughout this series, but in this example we will focus on the Fields part of it.

In order to do this we need to create an object which has an empty “Templates” object value. This “Templates” object then contains a “Fields” object value which contains an array specifying the fields we want to override. Each field override then refers to methods which contains the rendering logic for that field.

We finally pass our main object over to the RegisterTemplateOverrides method and let SharePoint take care of the rest. For example:

(function() {
  var mjhOverrides = {};
  mjhOverrides.Templates = {};

  mjhOverrides.Templates.Fields = { 

    ‘MyCustomField’: {
      ‘DisplayForm’: mjh.displayMethod
    }
  };

  SPClientTemplates.TemplateManager.RegisterTemplateOverrides(mjhOverrides );

})();

So in the example code above we create our override object called “mjhOverrides” (which has a “Templates.Fields” value).  We then assigned an array (of one item) which specified the InternalName of the field I want to override (in this case “MyCustomField”).

I then specified that when SharePoint wants to render this field for a “Display Form” then I want it to use my own method called “mjh.displayMethod”

The whole thing is wrapped in an anonymous self-executing function so that it executes as soon as the page is loaded but doesn’t pollute the global namespace.

Of course, you could specify multiple different fields or multiple different override methods, this uses simple JavaScript array principles and an example is shown below:

mjhOverrides.Templates.Fields =

{ 

  ‘MyCustomField: {
    ‘DisplayForm’: mjh.displayMethod,
    ‘View’: mjh.viewMethod
  }, 
  ‘Title’: {
    ‘DisplayForm’: mjh.displayMethod,
    ‘View’: mjh.viewTitleMethod
  }

};

So in the above example we are overriding two different fields (a custom field called “MyCustomField” and the out of the box “Title” field). For each field we specify overrides for both the DisplayForm and the View (List View) methods.

Note that we can re-use the same rendering method multiple times for different fields (so it is highly recommended to try and build reusable generic render methods where possible).

Format of a Render Method
So now that we have told SharePoint which render method we want it to use I suppose it would be useful to actually write it. Being a good JavaScript citizen we declared our own namespace for our functions so we didn’t pollute the global namespace, so the function starts off with a simple method declaration.

var mjh = mjh || {};

mjh.displayMethod = function (ctx) {
  return ‘<div>Hello World</div>’;
}

The format as you can see is very simple. All we need to do is return a string which contains the HTML we want to display. This example is not particularly useful as every item will render the same HTML (a simple Hello World message).

Hopefully you can appreciate that with the power of JavaScript and CSS you really do have full-reign to do whatever you want here. You can declare JavaScript events for AJAX REST calls or simply using some CSS and jQuery to create a funky dynamic interface (or just output some nice clean HTML).

However, this example isn’t terribly useful as what we REALLY want are access to the item values, and this is where the “ctx” object comes in. This is a method argument which SharePoint automatically provides and is a “Render Context” object.

Now I really haven’t been able to find very much information on MSDN / TechNet (read – actually I’ve found nothing) which describes this object and all of its methods, but from inspecting the JavaScript object using the developer tools I’ve managed to gleam a fair bit of detail. I’ve listed the basic values below, but to be honest you’d get a lot of value by poking around in the script debugger and checking out this object in more detail.

// value of the current field
var currentValue = ctx.CurrentFieldValue;

// the list item object
var item = ctx.CurrentItem;

// get the schema for the field
var field = ctx.CurrentFieldSchema;

So in order to make our display method a little more useful we should update it to the following:

mjh.displayMethod = function (ctx) {
  return ‘<div class=’mjhCustomField’>’ + ctx.CurrentFieldValue + ‘</div>’;
}

So now we have our item being displayed in a custom div with our own class. We can of course properly go to town on this but you get the idea 🙂

This is all then wrapped into a JavaScript file and attached either to the Site Column (declaratively in XML) or the List Form Web Part, or the Content Type (for more information on how to do that please go and read Part 1).

So that is about as complicated as it gets for Display Forms, but don’t worry, we have all sorts of fun and games coming up in the next parts in the series, first creating custom editing interfaces, providing validator methods and overriding views.

Next : Part 3 – Creating a custom editing interface

JSLink and Display Templates Part 1 – Overview, URL Tokens and Applying JSLink to objects

This is the first in a 4 part series about JSLink where I intend to go through all the ins and outs of using Display Templates to customise list rendering.

This first section really covers off the basics. It doesn’t contain any real sample code about the Display Templates (that is in Parts 2, 3 and 4) but does explain what JSLink is and how you can apply it to different objects.

What is “JSLink” exactly?
I think there has been a fair amount of confusion over what the terminology “JSLink” actually means. I’ve commonly seen it referred to as the technology which allows you to customising field and list rendering but that is really the Display Template functionality.

In a nut-shell JSLink simply means “link to my JavaScript file”

This is basically a URL to a JavaScript file. It doesn’t really matter where this file is (it could just as easily be in a document library or the Layouts folder). There are a vast number of objects you can attach JSLink references to but the ones we are really interested are:

  • Site Columns
  • Content Types
  • List Views
  • List Forms (e.g. New / Edit / Display forms)
  • List View Web Parts
  • List Form Web Parts

This gives us the full battery of places that we need in order to get our JavaScript in the right place at the right time, some of which are clearly desirable for different reasons.

JSLink URLs and Tokens
When you are constructing your JSLink URL there are a number of tokens you can take advantage of:

  • ~site – reference to the current SharePoint site (or “Web”)
  • ~sitecollection – reference to the current SharePoint site collection (or “Site”)
  • ~layouts – version specific reference to the web application Layouts folder (so it will automatically swap out /_layouts/14 or /_layouts/15 for you)
  • ~sitecollectionlayouts – reference to the layouts folder in the current site collection (e.g. /sites/team/_layouts/15)
  • ~sitelayouts – reference to the layouts folder in the current site (e.g. /sites/teams/subsite/_layouts/15)

This allows you to easily make sure that your JSLink files are targeted correctly (whether you are provisioning them to a specific library, or want to make sure your _layouts URL is constructed appropriately).

You can also apply more than one JSLink reference at a time by separating each reference with the pipe | symbol. So if you wanted to include two custom JSLink files on a field you might use the following attribute:

JSLink=~sitecollectionlayouts/MJH/JSLink1.js|~sitecollectionlayouts/MJH/JSLink2.js

Applying your JSLink References
You have a whole range of different options for applying your JSLink to the different objects, and this will largely depend on where you want your customisations to be applied.

If you are creating a new custom field type then you would implement it at the Site Column level. If you want to do something specific such as cascading drop-downs then you might want to do that at the Content Type or List (form) level.

If you are doing a one-off demo in an environment where you don’t have a high level of permissions then you can apply the JSLink references to the List View or Form Web Parts (although appreciate that this obviously doesn’t scale particularly well as you would have to manually apply it to each web part).

You can apply them using XML as part of your Site Column, Content Type or List View definitions. Each of these contains a JSLink attribute which you can use to populate a URL

JSLink=~sitecollectionlayouts/MJH/JSLink1.js

You can also apply them to the above, as well as list forms using Server Side Code (I’m not sure if there is a client side object model equivalent).

SPList list = web.Lists.TryGetList(“My List”);
if (list != null)
{  SPForm editForm = list.Forms[PAGETYPE.PAGE_EDITFORM];
  editForm.JSLink = “~sitecollectionlayouts/MJH/JSLink1.js”;
}

You can even do this in PowerShell if you are properly hardcore 🙂

$web = Get-SPWeb https://teamsite.mjh
$field = $web.Fields[“MJHSampleField”]
$field.JSLink = “~layouts/MJH/JSLink1.js”
$field.Update($true)

And finally you can set this in the List View Web Part or List Form Web Part using the web part properties:

Add your JSLink reference to Web Part properties

There is also a final option where it seems you can create re-usable templates by uploading your templates into the Master Page Gallery so they appear as new “View Types” when users are creating new Views for their lists, but more about that in Part 5!

So that covers all of the basics about what JSLink actually is, how the URLs are constructed and how you can apply them. In the next few parts we will be looking at the sample code and walking through some real-world examples of how you can use JSLink along with Display Templates to implement custom field and view rendering.

Next: Part 2 – Changing how individual fields display