Friday, 21 June 2013

SharePoint 2013 - Custom Field Type Controls - How can I use the JSLink Property for Rendering in the List View, but still Use Server Controls (e.g. Telerik Controls) for Edit and Display View?

You may know that in SharePoint 2013, you can now control how a field renders completely by using JavaScript via the new JSLink Property on field controls. An example of this can be found on MSDN at "How to: Extend the Geolocation field type using client-side rendering". What if you want to do JavaScript rendering for just the list view - and use fully featured controls for editing and item display?

This is not documented anywhere (I found this by trial and error and some help from .NET Reflector - http://www.red-gate.com/products/dotnet-development/reflector/) - but you can actually have both the JSLink render your field in your SharePoint list view and take full advantage of server rendering of controls (e.g. using Telerik AutoComplete for Token Selection) at the same time.

You can do this by overriding the JSLink property in your Field class (inheriting from SPField) as below so that it renders your full controls for Display/Edit and renders your JSLink for viewing in a list:

   public override string JSLink
        {
            get
            {
                if (SPContext.Current != null && SPContext.Current.FormContext.FormMode == SPControlMode.Invalid)
                    return "../_layouts/15/MyProjectName/CustomFieldControl.js";
                else
                {
                    return string.Empty;
                }
            }
            set
            {
                base.JSLink = value;
            }
        }

As above, this looks at the current SPContext to determine whether it is currently rendering in the list view (and renders the JSLink property) - otherwise, it just uses the default server control rendering behaviour.

DDK

No comments: