Friday, June 19, 2015

Hiding form fields using CSR without jQuery

A recent question on SharePoint.SE about the best way to hide fields on forms got me thinking.  Many people know about how to hide fields on forms using jQuery, by using some selector that gets you to the field's label on the form, and then hiding the containing <tr> to hide both the label and the field's control:

$('.ms-formtable nobr:contains("Field Display Name")').closest('tr').hide();

And this article shows how to apply that same jQuery technique using client side rendering / template overrides.  But I wondered, is there a way to hide fields on forms using just what you have available during CSR code execution?  Is there a way to do it without needing jQuery?

Indeed there is:

(function () {

    var overrideCtx = {};
    overrideCtx.Templates = {};
    overrideCtx.Templates.Fields = {
        "Field1": {
            "NewForm": hideField,
            "EditForm": hideField
        },
        "Field2": {
            "NewForm": hideField,
            "EditForm": hideField
        }
    };

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

// the hideField function uses ctx.CurrentFieldSchema.Name,  
// so it is generic enough to be used for multiple fields

function hideField(ctx) {

    // get the span that represents the field's actual edit control
    var span = $get(ctx.FormUniqueId + ctx.FormContext.listAttributes.Id + ctx.CurrentFieldSchema.Name);

    // still need to go up two levels to hide the entire <tr>
    span.parentNode.parentNode.setAttribute("style", "display:none");
    return "";
}

I guess it just goes to show you how much you can actually do with CSR.