SharePoint 2013 Conditional formatting in listviews

In SharePoint 2010 it was possible to implement conditional formatting via SharePoint Designer 2010 by using the following button:

cond_11

In XSLT you also could transform your columns in views and listforms to use images or like this.

This part has changed with SharePoint 2013. It is not possible to use the UI with preview of SharePoint Designer 2013 anymore now. But it is possible to use conditional formatting in a different way, which is also pretty cool.

In this post i would like to share some of my examples.

I created a list with Title, CreateDate (Date), Priority (Choice), PercentComplete (Number as Percentage), Marked (Yes/no)

cond_1

I would like to do the following things:

#1 CreateDate Column should have coloured background. Red if date is < today, yellow if it is today

#2 Priority should have red background if Priority is high

#3 PercentComplete should be a loading bar

#4 the complete row should be green backgrounded if it is marked

So that it looks like that:

Ok how can we do that?

First we open SharePoint Designer 2013 or we can also use notepad or notepad++. In fact we create a .js file which we put into the folder _catalogs/masterpage/displaytemplates

I call my file cond_formatting.js

cond_2

Now i open the file and do some editing.

But before editing, i will show you how to reference this file into you desired view:

You should go to your view and click on site settings menu and then edit page:

cond_3

Now you have to select the view webpart and click on Edit WebPart

cond_4

After that you insert the link to your .js file (~site/_catalogs/masterpage/Display Templates/cond_formatting.js) inside the miscelanous area at JS-Link

cond_5

Now we can start with coding:) Before you read on: Yes you have to do that for all views, but you can do that by using Powershell for example.

At first i add the following code block.
In this function i call define the template parameters, like fields and which function each field should use and i define how the highlighting row should be handled by the OnPostRender method.

#0 Preparation



(function () {
var condFieldCtx = {};

// Define template variable
condFieldCtx.Templates = {};

// Define your required fields and functions to call in each case.
// In our case the field is Progress
// Override Function is PatientProgressViewTemplate
condFieldCtx.Templates.Fields = {
"Priority": {"View": PriorityFormat},
"PercentComplete": {"View": PercentCompleteFormat},
"CreateDate": {"View": CreateDateFormat}
};

//conditional formatting for a complete row comes here
condFieldCtx.OnPostRender = [HighlightRowOverride];

// Register the template override with SP2013
SPClientTemplates.TemplateManager.RegisterTemplateOverrides(condFieldCtx);

})();


After doing so, we have to create each function for the 4 target we have. Do you remember them? Let’s do it step by step:

#1 CreateDate Column should have coloured background. Red if date is < today, yellow if it is today



function CreateDateFormat(ctx)
{
//Convert the CreateDate into a number with getTime()
//ATTENTION: We Split by using '/' if you turn to another language setting it might not working!
var CreateDate = new Date(ctx.CurrentItem.CreateDate.split('/')[2],ctx.CurrentItem.CreateDate.split('/')[0]-1,ctx.CurrentItem.CreateDate.split('/')[1]).getTime();

var today = new Date();
today.setHours(0,0,0,0);

var todayNo = today.getTime();

//Compare and react
if(CreateDate == 'undefined' || !CreateDate)
{
return ctx.CurrentItem.CreateDate;
}
else if(CreateDate < todayNo)
{
return "<span><font style='background-color:red;display:block;'>"+ctx.CurrentItem.CreateDate+"</font>";

}
else if(CreateDate == todayNo)
{
return "<span><font style='background-color:yellow;display:block;'>"+ctx.CurrentItem.CreateDate+"</font></span>";
}
else
{
return ctx.CurrentItem.CreateDate;
}
}


Result should look like this:

cond_6

#2 Priority should have red background if Priority is high



function PriorityFormat(ctx)
{
var priorityValue = ctx.CurrentItem.Priority;

if(priorityValue == 'High')
{
return "<span><font style='background-color:red;display:block;'>"+ctx.CurrentItem.Priority+"</font></span>";
}
else
{
return ctx.CurrentItem.Priority;
}

}


Result:

cond_7

#3 PercentComplete should be a loading bar



function PercentCompleteFormat(ctx)
{
var returnvalue = '<div style="background: #BCBCBC; display:block; height: 20px; width: 100px;"><span style="color: #fff; position:absolute; text-align: center; width: 100px;">'+ctx.CurrentItem.PercentComplete+'</span><div style="background: #D2421F; height: 100%; width: '+ctx.CurrentItem.PercentComplete.replace(" %", "")+'%"></div></div>';
return returnvalue;

}


Result

cond_8

#4 the complete row should be green backgrounded if it is marked



function HighlightRowOverride (ctx)
{
for(var i=0; i < ctx.ListData.Row.length; i++)
{
var listItem = ctx.ListData.Row[i];
var iid = GenerateIIDForListItem(ctx, listItem);
var row = document.getElementById(iid);

if(listItem.Marked == "Yes")
{
row.style.backgroundColor = "rgba(4,92,8,0.1)";
}
}
ctx.skipNextAnimation = true;
}


Result

cond_9

So in the end, you can do so many cool things with these options. It is really great. My list looks like this now:

Youcond_10

You can download my code here, there you got all the functions i posted above.

UPDATE:

If you did not deactive MDS (Minimal Download Strategy) Feature in the web feature area, you might get some terrible effects.

cond_12

It won’t show the conditional formatting all the time, it will show it if you’re hitting STRG+F5 but that’s not what user like to do all the time. So you have two options. Option 1 you deactivate the feature and everything is good, or you read my next post and have to change a little bit the code, but then everything is ok 🙂

Some cool examples i found at my research and which i can recommend to read, cause you see what cool stuff is possible in SharePoint:

Example for a tasklist (Percent Complete and DueDate)
Applying JS Link on Task Lists Breaks the Default Rendering of the Checkboxes

Example of highlighting a row
JS Link – Highlighting a Row with CSR

Example of highlighting column category
SharePoint list conditional formatting with JSLink

Example of a custom column
SharePoint Conditional Formatting by Laura Rogers

The article or information provided here represents completely my own personal view & thought. It is recommended to test the content or scripts of the site in the lab, before making use in the production environment & use it completely at your own risk. The articles, scripts, suggestions or tricks published on the site are provided AS-IS with no warranties or guarantees and confers no rights.

Karsten Pohnke About Karsten Pohnke
He is Consultant for SharePoint Solutions for collaboration, communication and business processes. He provides his customers applications based on standard features as well as development or combining the power of several microsoft tools like Dynamics CRM. In his free time he tries to collect tipps and worthy experience in this blog.

26 comments on “SharePoint 2013 Conditional formatting in listviews

  1. Hello Karsten, I have included a video showing my efforts to try to get the js file to work and for the conditional formatting to happen. I am on a Development box with SharePoint 2013 SP1 March 2015 CU. I created a brand new web application with NO MDS and I hopefully showed, in the video, the steps that I have taken. I created a custom list and put in the same column names and data as you. I was not able to get any of the “colors” to work. I have not changed any of the CSS / formatting, as it’s brand new “out of the box”
    http://www.screencast.com/t/wj4ZFdmar
    Thank you again! Matt

    • Hi Matt,
      did you refresh the page using STRG+F5?
      Another point is, do you know the debugger in IE? You can open it by hitting F12 and go to the script, set some breakpoints and afterwords start debugging you can see if it is using your script or if there some errors.
      If you like i can write you an email or could invite you to a lync session to look at your problem.
      Kind regards
      Karsten

    • I’m having the exact same issue. Any ideas?

  2. Mike Smith

    I’m getting the following error: Uncaught ReferenceError: HighlightRowOverride is not defined on this line:

    //conditional formatting for a complete row comes here
    condFieldCtx.OnPostRender = [HighlightRowOverride];

  3. I have something very similar to your code but mine does not work when I use any of the filter or search options on my list. I’m curious if you have the same issue?

  4. musikfipsi2003

    In your example, the background color is set to the text background. What if I want the whole cell background color set?

    • Then you use a div tag like in “#3 PercentComplete should be a loading bar” around the value and set the background color of the div.

  5. There is a SharePoint product that does conditional formatting in lists and document libraries. It also allows to resize columns, change font styles and colors and many more – it is called List Booster. Check it out at http://www.spbooster.com – works in SharePoint 2013 and SharePoint Online.

  6. Here is the German CreateDate format code:

    function CreateDateFormat(ctx)
    {
    //Convert the CreateDate into a number with getTime()
    //ATTENTION: We Split by using '/' if you turn to another language setting it might not working!
    var CreateDate = new Date(ctx.CurrentItem.CreateDate.split('.')[2],ctx.CurrentItem.CreateDate.split('.')[1]-1,ctx.CurrentItem.CreateDate.split('.')[0]).getTime();

    var today = new Date();
    today.setHours(0,0,0,0);

    var todayNo = today.getTime();

    //Compare and react
    if(CreateDate == 'undefined' || !CreateDate)
    {
    return ctx.CurrentItem.CreateDate;
    }
    else if(CreateDate < todayNo)
    {
    return ""+ctx.CurrentItem.CreateDate+"";

    }
    else if(CreateDate > todayNo)
    {
    return ""+ctx.CurrentItem.CreateDate+"";
    }
    else if(CreateDate == todayNo)
    {
    return ""+ctx.CurrentItem.CreateDate+"";
    }
    else
    {
    return ctx.CurrentItem.CreateDate;
    }
    }

    Thank you for the great post!

  7. Tom Ramsay

    Hi I have followed your code and can make it work great, but I have spet the last 4 hour try to make it work with English UK Date of DD/MM/YYYY and are pulling my hair out what’s left of it can you help please, Tom

  8. Tom Ramsay

    Hi I have now figured out how the date works for UK DD/MM/YYYY and have got it working on now I am trying to change the name of the column from CreateDate to ResponseDate can you help or advised, Thanks Tom

    • Maciek

      It’s wonderful that you told us you got it sorted, but it would be tremendous if you told us HOW?

  9. Karsten, hi, I’m experiencing the exact issue that the first commenter (Matthew) so comprehensively captured on screencast. I’m hoping you resolved his issue and if so, can you share what the resolution was? Thank you. This would be a great solution.

  10. Denisse

    I have a Field that has space in it, how do I use listItem.Job Status == “Estimated” in the code? Can anyone help?

    TIA

    • hi, if you use the debugger in IE you can get the correct fieldname if you have other special characters.
      For a space you can use Job_x0020_Status – “_x0020_” is the replacement for an empty space character.

  11. Hi. I have multiple yes/no columns in each row. I need to change each cell to display red/green depending on whether the value is yes/no. How do I do this? Also, when I upload the script to the masterpages file, to I upload it as a design file or a javascript design file? The second has mandatory fields that require URL’s. What are these? Thank you

  12. Simone Righetto

    Hi Carsten,
    does your solution apply also to SHP2013 Foundation?
    Thank you,
    Simone

  13. Janssens, Dimitri

    Dear Karsten –

    Nice post and I really like the approach and how it’s brought. But I simply can’t get it to work from my end :-(.
    Fyi I am working on SharePoint 2013 online version & MDS is deactivated, could this be the issue?

    Short summary of what I did.
    I created the js file, Linked it to my list view and added the following code to my js file. I only have one column which I want to highlight and it’s called ‘status’.
    This is the code, if you would have any ideas or thoughts they will be more than welcome:

    (function () {
    var condFieldCtx = {};
    // Define template variable
    condFieldCtx.Templates = {};
    // Define your required fields and functions to call in each case.
    // In our case the field is Progress
    // Override Function is PatientProgressViewTemplate
    condFieldCtx.Templates.Fields = {“Status”: {“View”: PriorityFormat}};
    //conditional formatting for a complete row comes here
    //condFieldCtx.OnPostRender = [HighlightRowOverride];
    // Register the template override with SP2013
    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(condFieldCtx);
    })();

    function PriorityFormat(ctx)
    {
    var priorityValue = ctx.CurrentItem.Status;
    if(priorityValue == ‘Not Approved’)
    {
    return “”+ctx.CurrentItem.Status+””;
    }
    else
    {
    return ctx.CurrentItem.Status;
    }
    }

  14. Adarsh Gumashta

    When these 3 functions are called ?

    PriorityFormat
    PercentCompleteFormat
    CreateDateFormat

  15. Pingback: Sharepoint CSR JSLink – View Cell Customization | Uask

  16. Maciek

    Karsten,

    I got majority of your code working, except for the date, probably because I’m using UK date format.

    Are you able to help?

Submit comment

Allowed HTML tags: <a href="http://google.com">google</a> <strong>bold</strong> <em>emphasized</em> <code>code</code> <blockquote>
quote
</blockquote>

Please fill in the captcha: * Time limit is exhausted. Please reload CAPTCHA.