Tuesday, March 22, 2016

Re-purposing the Title Field of a list

A posting on LinkedIn discussing what to do with the Title Field when it's not needed inspired this post.  Once I find the discussion again on LinkedIn, I will post :)

I have a love/hate relationship with the Title field.  It's great in views because it can link directly to the list item.  It's a pain because every time you create a list, you have a title field and it may not be necessary.  Some people choose to hide the field, others re-purpose it.  I fall into the latter category for a couple reasons, but in particular one big reason:  my end users love having the Title field linked to the edit menu on most views.

If I really have no reason for the Title field, I will do one of two things:

  1. Give the Title field a default value of "View Item".  This looks great in views, but when a user goes to edit the item or create a new item, they can edit the Title.
  2. Give the Title field a default value of "New Item" and create a workflow to assign a new title based off the Item's ID number.  For example, for a list of task items, I might have a workflow assign a Title of TASK:25, where 25 is the item's ID.  Again, this looks great in views, but users can modify the Title still.
So, what to do?  What I have laid out is an okay solution, but not really complete.  We can use JavaScript to make the field read-only!

If you haven't used JSLinks before, there are a number of great tutorials out there.  Here is a link to a number of great examples.

Here is the Script I typically use and should work with any list.  In my code below, the script makes the Title Field read only and displays the field in bold text.  Feel free to use this code and modify as you see fit!

(function () {
    var ctx = {};
    ctx.Templates = {};
    ctx.Templates.Fields = {
        "Title": {
            "NewForm": readOnlyFieldBold,
            "EditForm": readOnlyFieldBold,
            "DisplayForm": titleFieldTemplate
        }
    };
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(ctx);
})();

function readOnlyFieldBold(ctx) {
    var formCtx = SPClientTemplates.Utility.GetFormContextForCurrentField(ctx);
     
    return "<b>" + formCtx.fieldValue + "</b>";
}

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

    return formCtx.fieldValue;
}

function titleFieldTemplate(ctx) {
    var titleField = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];

    return "<b>" +titleField + "</b>";
}