SharePoint Conditional Formatting

228-image_ee6d8804-8896-484f-a893-cb5aa3fe6b86_7725B0D1.png

In SharePoint 2013 and Office 365, there is no more design view in SharePoint Designer, and of course InfoPath is slowly being depreciated between now and 2023.  Without these tools, how do we go about creating business solutions easily like we have been doing for years?  I’m not a programmer, and I know that most of my audience here… you’re not programmers either.  Well, there’s this thing called JSLink that was introduced in SharePoint 2013.  It is another tool we can use to create fairly simple conditional formatting and lots of other formatting on our forms and views… except it entails JavaScript.  Some of it is so simple that even *I* can do it.  I found a ton of blog posts  where developers (a lot even friends of mine) have been blogging about cool capabilities and tricks for a couple of years now.  The thing is, the people who read these blogs are also developers, so that’s who they’re tailored to.  Most of them don’t bother stating the basics like “what is a JS file and where do I put it?”, because their readers already know this stuff.

In this post, I will show you, the non-developers how to use JS Link, and some extreme basics about how it works.  Once you are armed with this knowledge and you want to research it further, you will better be able to translate what the developers are writing and maybe be able to use it.

Here we go, and remember that I am not a programmer and I don’t know anything technical, I’m just figuring it out as I go.  This blog post was my inspiration.

Okay, I’m going to use a super simple example here, because mostly what I’m demonstrating is not the script language and how to program, but how to get JSLink actually working in your environment.  Again, this is really cool to me, because it allows us to do conditional formatting in views and forms without the need for SharePoint Designer or InfoPath!  The example is a SharePoint list of patients in a hospital.  There is a column called “Progress Level”, and their level is either “Good” or “Bad”.  Very simple.  I want to show the good ones with green text and the bad ones in red.  Actually, in order to demonstrate an image in conditional formatting versus a text color, the good ones will show in green text, and the bad ones will show a red icon, like this:

228-image_ee6d8804-8896-484f-a893-cb5aa3fe6b86_7725B0D1.png

So here are the steps to do this:

  1. Create a custom list with a choice column in it called Progress.  Make the two choice options Good and Bad.  When you create this column, make sure you call it Progress, and you’re not just renaming some other column and calling it that.  This is important to making it work correctly.
  2. Insert this new list on your homepage or some page on your SharePoint site, as a web part, and make sure the Progress column is showing.
  3. Download this file to your computer and extract the zip.  It’s just a text file, but you’ll need to save it as a .JS file.  See, I removed the .TXT and changed the Save as type to All Files.
    PatientList.js
    228-image_ee4307e4-a365-4ee6-a782-6a33f4fb00f8_7725B0D1.png
  4. Download these image files to your computer:  RedGreen  Go to the root of your site collection, and to the default Library called Site Assets.  Upload these images to it.  The JavaScript file will reference that as the location of the indicator.
  5. If you have access to the root level of your site collection, go there and go to Site Settings.  In the Web Designer Galleries section, click Master Pages.  Then click the Display Templates folder.
  6. In this library, go to the Files tab of the ribbon, click the Upload Document button, pick your JS file you downloaded in step 3, and choose Javascript Display Template as the content type when prompted to fill in metadata.
  7. Here is what you are prompted with, and what to fill in, and click SAVE.
    228-image_18accdea-abf2-4210-ae8a-7e3ebd6c92b3_7725B0D1.png
  8. Here are what some of the settings mean:
    Target Control Type:
    View – a view in a list of multiple items
    Form – a form that users are filling out, such as dispform/editform/newform.
    Field – just a single field, although I can’t find any references that really explain what this one is for and when it would be used.Standalone: Every reference I’ve seen says to set this to Override, but no one says what the purpose of the other option (Standalone) would be.

    Target Scope: This is the URL relative to the site collection.  So here I put a / because I want this JS file to be available to use anywhere in the site collection.  If I only wanted to be able to use this code on a sub-site called “IT”, I would type /IT in this box.

    Target List Template ID:  The list in my example is a custom list (see step 1), and the code for a custom list is 100Here is a list of a bunch of other codes for the other list types.  Scroll down to the section called Type, to see the long list of codes.  I know it says 2010, but I can’t seem to find a list of updated codes for the latest version.  There are only one or two new list types in 2013, and the rest are going to be the same.

    If you’ve got your file uploaded now, you can skip to step 12.

  9. If you don’t see the JavaScript Display Template at step 4, or if you don’t have access to the root of the site collection, here are your different instructions instead of step 4.  Create a document library on your site, and name it whatever you want.  I’m just calling mine “Test Files”.  In the Library Settings, go to Advanced Settings, and change Allow management of content types to YES.
  10. On your library settings page, in the content types section, click Add from existing site content types.  Choose JavaScript Display Template, add it, and click OK.
    228-image_ff563d70-880c-4d48-b828-3840a9eb427e_7725B0D1.png
  11. Go to step 6.
  12. Anyway, now that your JS file has been uploaded, you’ll need the URL to it.  In the Files tab of the ribbon, click the View Properties button for this JS file you just uploaded.  Right click on the name of the file and click Copy Shortcut.
    228-image_88b16793-7663-4bdd-9410-68a4476afa3c_7725B0D1.png
  13. Now that you have the URL to the JS file, remember that web part from step two?  Go to that web part in the browser, and open the web part properties toolpane.  Expand the Miscellaneous section (more on that in my other post).  Paste your URL in the JS Link box.  Notice that when you save the web part, nothing magical happens.  Go back into the web part properties and notice that the URL is now showing as relative, like since my library is “Test”, it changed the URL to /Test/PatientList.js 

    You need to put the ~site at the beginning, as shown here.  If your JS file were being stored in a library at the root of your site collection, and you were referencing it from web parts in sub-sites, you would use ~sitecollection instead.
    228-image_17da9315-d6bd-40c1-9012-3dd5b2593a5d_7725B0D1.png

Now, save your page, and your web part looks like that that first screenshot (at least the progress column does).  At step two, I instructed you to put your list on a page as a web part, but if you want to you can just go to any regular view of your list, click the (Settings) gear at the top right and click Edit Page.  From there you can do step 13.

9/29 update:  I see some confusion out there around this last step of using the link to the JS file.  Please refer to a seperate blog post I wrote called SharePoint URL Basics.  This will help you understand how to obtain the link to your site.  In my example screenshot above, “Test” is a library in my site, and PatientList.js is a file in that library.

Wes Preston has a great blog, with a lot of posts about JS Link, and here’s a great “primer” that he wrote about it.  There are also hundreds of other blog posts out there about JS Link.

http://www.idubbs.com/blog/2012/js-link-for-sharepoint-2013-web-partsa-quick-functional-primer/

I’ll get into dissecting the syntax in another post.  In the meantime, feel free to dig in and see how the conditional formatting works, and browse the plethora of posts about it.

30 comments

  • Great post Laura!

    While JS coding can intimidate some, it really is MUCH simpler than old XSLT from 2010/2007.

    Ironically just today I was showing a co-worker CSR samples on MSDN at http://code.msdn.microsoft.com/office/Client-side-rendering-JS-2ed3538a Easy to copy, paste, and adapt to your needs.

    Cheers!

  • Thanks Jeff for the link!

  • Hi Laura,
    Very easy to read/follow post…. although in my case, I can’t seem to get the formatting to change. We are just building out our new 2013 Environment so that may be impacting it.

    Since I don’t get any error messages, is there a way to trace down what might be causing the formatting not to work? Right now it just looks like the default viewing.

    Finally a general question… Since Communities and Blogging are a new concept for me (at least in work environment), I was curious how you decide what would make a good blog post vs a Discussion post?

    One week into my new site, I’m finding topics that could fall into both places. Given our corporate culture (still locked in email and net work drives), I have a feeling no one would even click on the “Blog” link to see that content.

    Thanks again for this post. It has really opened my eyes to new possibilities.

    Mike

  • Mike Z,
    For troubleshooting, I’ve had to play with my URL structure because I had done it as absolute instead of relative, and for your conditional formatting, start with something super simple like bold just to make sure that isn’t the part that’s wrong.

    For blogging, I usually blog about ideas and things that I figure out, and for stuff like Yammer, that’s where I ask questions about maybe the best way to do something.

  • I’m so embarrassed to ask this but… Step 3 “Download this file to your computer”. What file are you referring to and how should I download it?

  • I have some column names that have a space in them, such as “Patient Name”. How do you use names like this, I tried putting them in quotes such as:

    var _PatientName = ctx.CurrentItem.”Patient Name”;

    but it doesn’t work.

    And your step 1 says you can’t rename columns, so I can’t even simply rename it to “PatientName”, I’ve tried that and it doesn’t work.

    So do I need to recreate my list with single-word column names?

    Thanks, and I watch a lot of your Rackspace youtube videos, you do a great job explaining a lot of Sharepoint issues!

    I am @dibbt on twitter!

    Thanks!

  • mam how we hide edit link according to statuswise in sharepoint2013 plz tell

  • @Laura
    >you’re not programmers either

    Not entirely true. Your blog has been really helpful for me as a programmer new to SP. Sometimes I’m a little to quick to jump to a code solution, when a non-code one may work better. Thanks!

    @Kevin,

    You need to refer the the field by its internal name, not its display name. This means that spaces and other non-alphanumeric characters are converted to unicode, and the entire thing is capped to 32 characters. Renaming the field does not change the internal name.

    “Patient Name” becomes “Patient_x0020_Name” since 0020 is the character code for ” “.

    You can get explore all the properties of a variable (such as ctx) by outputting it to the browser’s developer console with

    console.log(myvariable)

  • Kevin,

    var _PatientName = ctx.CurrentItem[“Patient Name”];
    or
    var _PatientName = ctx.CurrentItem[“Patient_x0020_Name”];

    You can access every property in JavaScript by using the dot notation or by using square brackets with a string.

  • Hi laura,
    With the lost of the graph webpart from SP2010, do you have any good recommendation on how to create a dashboards with graphs?

  • Hi, Laura.

    The List Tools is missing after changes.
    How to set focus in list view?

    Thanks for help

  • Thx Laura!
    The code and JSLink method work great. One question though. When I first navigate to the site where the web part of the list and the color-coded field reside, the color displays beautifully. But then, if I click on the site’s quick links in the left navigation and leave the page and then come back (to the page to the web part), the coloring is gone. Same thing happens if I edit one of the list items (row) in the list (in web part). The text in field is black, no color. The only way I can get the color to display again is by leaving the site altogether and reentering it.

  • Hi Laura!

    Thank you so much for your great manual! It presents the perfectly simple introduction of the JSLink capabilities for newbies! It took me half an hour to understand everything and adopt the code for my needs, you saved me a lot of time, and saved me from the lot of headache )

    Best regards, Ulia.

  • I’m attempting to use conditional formatting in a field of an external list displayed on a home page of a site collection on SharePoint 2013. The script below temporarily works if I add it on the page, but I have an auto refresh in the webpart and after it refreshes the formatting disappears.

    I’ve attempted using JS Link but it doesn’t work for me. The Target List Template ID’s I’ve tried are 101, 100, and 600. That would be one of my questions – which to use because I didn’t see any solid resource on this. Could you confirm what ID to use? Also could you provide an example on how I could use this code with JS Script? This might help it sink in for me. 🙂

    https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js

    $(document).ready(function(){

    $Text = $(“td”).filter(function() {
    return $(this).text() === “1-Urgent”;
    }).css(“background-color”, “#B22222”);

    $Text = $(“td”).filter(function() {
    return $(this).text() === “2-High”;
    }).css(“background-color”, “#E6B88A”);

    $Text = $(“td”).filter(function() {
    return $(this).text() === “U”;
    }).css(“background-color”, “#C14E4E”);

    });

  • This code is slick and allows for multiple column renderings.

    // List View – Priority Color Sample
    // Muawiyah Shannak , @MuShannak

    (function () {

    // Create object that have the context information about the field that we want to change it’s output render
    var priorityFiledContext = {};
    priorityFiledContext.Templates = {};
    priorityFiledContext.Templates.Fields = {
    // Apply the new rendering for Priority field on List View
    “Step1”: { “View”: priorityFiledTemplate },
    “Step2”: { “View”: priorityFiledTemplate },
    “Step3”: { “View”: priorityFiledTemplate },
    “Step4”: { “View”: priorityFiledTemplate },
    “Step5”: { “View”: priorityFiledTemplate }
    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(priorityFiledContext);

    })();

    // This function provides the rendering logic for list view
    function priorityFiledTemplate(ctx) {

    var priority = ctx.CurrentItem[ctx.CurrentFieldSchema.Name];

    // Return html element with appropriate color based on priority value
    switch (priority) {
    case “No”:
    return “” + “Incomplete” + “”;
    break;
    case “Yes”:
    return “” + “Complete” + “”;
    break;

    }
    }

  • I have used this for a couple of sites. I have a new one im working on and for some reason when I designate a jslink file the view returns no rows. This happens even if the jslink file is an blank file. No js errors or anything like that. Just empty query. If I remove the jslink, i get my view back. Any thoughts?

  • Suz, here is the link to the list of codes: http://msdn.microsoft.com/en-us/library/ms462947(v=office.12).aspx
    Sorry, but I don’t know how to troubleshoot your code because I’m not a developer.

    Adrian,
    Thanks!

  • I’ve been trying to find the answer to this question but have not had any luck. Hoping you can help me.

    I want to do conditional formatting on a field, but instead of an exact match. I want if a field ‘contains’ a term or phrase?

    Is this possible with JSLink?

  • Hi Laura

    here is a copy of my code to color code a “MaxEnddate” field if is within the next 180 days:

    (function () {
    var statusFieldCtx = {};

    statusFieldCtx.Templates = {};
    statusFieldCtx.Templates.Fields = {
    “MaxEndDate”: {
    “View”: ColorCodeDueDate
    }
    };

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

    function ColorCodeDueDate(ctx) {
    var dueDate = new Date(ctx.CurrentItem.MaxEndDate);

    var now = new Date();
    var then = new Date();
    then.setDate(now.getDate() + 180);

    // if there’s no due date don’t render anything
    if (dueDate == ‘undefined’ || !dueDate) {
    return ”;
    }
    else if (dueDate >=now && dueDate <= then) { // we are within 180 days
    return "” + dueDate.toLocaleDateString(‘en-GB’) + “”;
    }
    else { // we are outside of 180 days
    return “” + dueDate.toLocaleDateString(‘en-GB’) + “”;
    }
    }

    Any idea as to why it is not formatting the date correctly to dd/MM/YYYY, even though the locale of my site is set to English United Kingdom?

  • Great insight. I did not figured out what is messing up and then saw the usage of ~site in the beginning of JSLink URL needed, that really helped.

    Keep it up

  • Hi Laura,

    as a novice in SharePoint 365, I have tried to link a js-script to a List-webpart using JS Link.
    But when I create a new custom list (totally out of the box) on one site, I have the option in webpart miscellaneous tab for JS LINK.
    But on a other site, again with a new custom list (totally out of the box), in micsellaneous tab the JS LINK is missing!
    Why is the JS Link missing is some webpart/sites?
    Where lays the difference between those?

  • Hi Michiel, it’s probably because of the view style you’re using. In the view settings, go to the Style section, and choose the one called Default. Then, those extra web part properties will magically appear.

  • Hi Laura,

    Thanks for this. Everything works except for one thing. I am using Shaded as the view style but looks like the *.js file overwrites and using the default. Do I need to add anything to the code so it will use my selected view style?

  • First of all thank you! What a great article! I’ve just one problem…It’s just working for myself! all the other users don’t see the outcome. Seems to me that the script isn’t even running for them. Is there any setting I’ve missed to set? Unlike you I have to make use of the Miscellaneous Section of the Jslink, but this shouldn’t be an issue, right? Thank you very much in advance for your help. BR, Tim

  • First I love this site, has any worked with project server, project center? The project manager on my team would like to color code the rows in the project center web part based on a column value. For example, she would like to have the background color grey if the % complete is 100 showing at a glance that the project has been completed. Any leads would be greatly appreciated. Thank you Laura for creating this site.

  • I am wondering and new at this (since an upgrade broke the calculated column use!) if anyone has written js code to change the font color of value in a different column based on the value of another column? I am receiving ‘undefined ‘ in the column I’m basing the condition on. The conditional column is changing font colors! strange!..
    I’m using the js file in jslink ..
    (function(){
    var fieldCtx = {};

    fieldCtx.Templates = {};
    fieldCtx.Templates.Fields = {
    “Status”:{“View”:ShowRed},
    “Total_Variance_for_PO_x003a”:{“View”:ShowRed}

    };

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(fieldCtx);

    })();

    function ShowRed(ctx) {

    var variance = ctx.CurrentItem[“Total_Variance_for_PO_x003a”];
    var statusck = ctx.CurrentItem[“Status”];

    if (statusck == “over”)
    {
    return “” + variance + “”;

    } else if (statusck == “under”)
    {
    return “” + variance + “”;
    }
    else {
    return variance;
    }
    }

Leave a Reply