Tuesday, April 24, 2007

Conditional Formatting on a Sharepoint List View

When using the sharepoint list view there is no way to have conditional formatting unless you convert it to a XSLT view within frontpage. Unfortunately when you do this you loose some features which you had eg. count. There are some issues with the filter functionality in the xslt web part. I have written some javascript which allows you to do conditional formatting on the client side. Just add it to a content editor web part after the view.

I will paste the javascript here shortly
As Promised
<script>
/*******************

Copyright (c) 2007 Tim Leyden

This script can be used freely as long as all

copyright messages are intact.

********************************/
function format(textconfieldname, textcondition,formatfieldname,openformattag,closeformattag,tableid,islookupfield){

var cfindex; //the cell index of condition field
var ffindex; // the cell index of format field

var array = document.getElementsByTagName('th');
for (i=0;i<array.length;i++){
if(array[i].innerText != null){
//alert(array[i].cellIndex +" "+ array[i].innerText.substr(array[i].innerText.length-textconfieldname.length,textconfieldname.length));
if(array[i].innerText.substr(array[i].innerText.length-textconfieldname.length,textconfieldname.length) == textconfieldname){
cfindex = array[i].cellIndex;
}
if (array[i].innerText.substr(array[i].innerText.length-formatfieldname.length,formatfieldname.length) == formatfieldname){
ffindex = array[i].cellIndex;
}
}

}

var table = document.getElementById(tableid);
var rows = table.rows;
for (i=0;i<rows.length;i++){
var cells = rows[i].cells;
if (cells[cfindex]!=null){
if (cells[cfindex].innerHTML == textcondition){
var name = cells[ffindex].innerHTML;
if(islookupfield){
name = name.replace (/self>(.*)(<\/A>)/,"self>"+openformattag+"$1"+closeformattag+"</a>");
cells[ffindex].innerHTML = name;
}else{
cells[ffindex].innerHTML = openformattag+name+closeformattag;
}


}
}
}
}
/*
example
params "field to check","value",field to format,"before tag","after tag","Html table id(this stays the same unless you change views","bool is it a lookupfield"
format("VIP","Yes","Phone Number","","","{BEEFD7E9- HTML TABLE ID(use view source to retrieve)-F03FDA1BA528}",false);
this will format the phone number as bold for all people who have the VIP field set to yes
*/
</script>

The script relies on the fact that the list view web part always outputs its html table in the same predictable format. You may need to make some changes to suit your application