Navigation

Wednesday 28 August 2013

Changing Site Contents from a Grid to a List

This is something that has been bugging me for a while, and something that has clearly been bugging my users (as they keep saying they can never find anything).

The problem with the tile view is that you have to scan both left-right as well as up-down to find the item you are looking for. With a large number of lists this quickly becomes extremely painful to find what you are looking for.

The standard "Site Contents" view .. in all its nasty tile-layout glory

So I thought, how could you turn it back?

Well, the good news is that the Site Contents view is actually all formatted using CSS with unique IDs and classes, which makes it a snip. the sample I've done below is in jQuery (because it is easy to pin a JavaScript file to every page and it works with Office 365 just as well).

So first off we need ourselves a function to reset all of the

function HideTiles() {
  $("#applist .ms-vl-apptile").css({ "display": "block" });
  $("#applist .ms-vl-apptile").css({ "min-height": "50px" });
   $("#applist .ms-vl-appinfo").css({ "min-height": "50px" });
  $("#applist .ms-vl-appinfo").css({ "width": "500px" });
  $("#applist .ms-vl-appimage").css({ "height": "50px" });
  $("#applist .ms-vl-appimage").css({ "width": "50px" });

  $("#applist #apptile-appadd .ms-vl-appimage").css({ "width": "96px" });

  $("#applist .ms-vl-appimage a.ms-storefront-appiconspan").css({ "height": "50px" });
  $("#applist .ms-vl-appimage a.ms-storefront-appiconspan").css({ "width": "50px" });
  $("#applist .ms-vl-appimage a.ms-storefront-appiconspan").css({ "line-height": "50px" });

  $("#applist img.ms-storefront-appiconimg").css({ "height": "50px" });
  $("#applist img.ms-storefront-appiconimg").css({ "line-height": "50px" });
  };

Then we need to actually make sure this gets executed. The problem here is that the Site Contents is rendered on-the-fly using JavaScript so we have to resort to a little Script on Demand to get this working.
 


$(function () {
  ExecuteOrDelayUntilScriptLoaded(HideTiles, "sp.ui.allapps.js");
});

Then the only thing needed is to make sure this script gets dropped onto the page and I've done this using a Custom Action (I could have used a delegate control with CSS style tags but that doesn't work in the Sandbox, i.e. Office 365)

<CustomAction
  ScriptSrc="~SiteCollection/_layouts/15/MJH.JSLink/MJH.AddCss.js"
  Location="ScriptLink"
  Sequence="20">
</CustomAction>

So if you set this up it looks something like this.


New formatting (in a single alphabetical list)
Now I admit, the formatting is pretty crude and it could do with a certain amount of smartening up, but the principle is sound and at least the owners of sites with large numbers of lists get an easier to navigate list which is alphabetical, instead of having to scan a page of dozens of tiles.

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 (coming soon)

Tuesday 27 August 2013

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'";
    }
    return new 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:
http://sdrv.ms/15eB6CI

....

Next -
Part 5 - Creating Custom List Views


Friday 23 August 2013

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:
 http://sdrv.ms/14KtFgv

...

Next - Part 4 - Validating user input