SharePoint Client Side Rendering – Default Field Rendering

Using CSR / JSLink to modify forms and views is a very powerful tool that can be used to great effect.  You can use SharePoint essentially out of the box and get more powerful features without having to rely on 3rd party embellishments.

Using methods outlined on other blogs such as https://www.codeproject.com/Articles/610259/SharePoint-Client-Side-Rendering-List-Forms gives you the outline of how to do this.  You can render the value with your own JavaScript  to get the result you like.

What if you want to render a field in the default SharePoint manner but with an extra class added, or you wish  to render the display version of the field instead of the edit version?

Well as outlined here: https://stackoverflow.com/questions/31516512/js-field-rendering-return-standard-field-rendering you can incorporate the correct default renderer you wish.

However – what if you don’t know what the field type is or what the form type is?  A nice generic function would be nice.  Well after digging down into the MS code gives you can try this:

function renderDefaultField(ctx, baseViewID) {
    if (baseViewID)
        return SPClientTemplates._defaultTemplates.Fields.default.all.all[ctx.CurrentFieldSchema.Type][baseViewID](ctx);
    else
        return SPClientTemplates._defaultTemplates.Fields.default.all.all[ctx.CurrentFieldSchema.Type][ctx.BaseViewID](ctx);
}

This can be used in the following way:

(function () {
    var context = {};
    context.Templates = {};
    context.Templates.Fields = {
        'Field1': {
            'NewForm': showMyField
        },
        'Field2': {
            'NewForm': displayMyField
        }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(context);
})();

and implemented thusly:

function showMyField(ctx) {
    return '<span style="color:red">' + renderDefaultField(ctx) + '</span>';
}

or overriding the display type:

function displayMyField(ctx) {
    return '<span style="color:red">' + renderDefaultField(ctx, 'DisplayForm') + '</span>';
}

Easy!

Leave a Reply

Your e-mail address will not be published. Required fields are marked *