Conditional formatting in item view (display form) using CSR / JS / CSS - is it doable?
-
22-12-2020 - |
Pergunta
Is it possible to apply conditional formatting to an item view [Display-Form] just like in the list?
I use SharePoint Online, Cisar and SharePoint extensions for Chrome.
Solução
You only have to take into account that the ctx
object is different for Views and Forms:
This CSR code works in both View and Form (no need for a 90KB jQuery library):
SP.SOD.executeFunc("clienttemplates.js", "SPClientTemplates", function() {
function colorStatus (ctx) {
var item = ctx.CurrentItem || ctx.ListData.Items[0];// View OR Form
var value = item.Status;
var color = { 'Not Started' : 'lightgreen',
'Closed' : '#FFF1AD',
'In Progress' : '#FFD800',
'Active' : '#01DF3A' } [ value ];
return String.format("<span style=background:{0}>{1}</span>" , color , value );
}
function init() {
SPClientTemplates.TemplateManager.RegisterTemplateOverrides({
Templates: {
Fields: {
"Status": {
View: colorStatus,
//EditForm: colorStatus,
DisplayForm: colorStatus,
//NewForm: colorStatus
}
}
}
});
}
RegisterModuleInit(SPClientTemplates.Utility.ReplaceUrlTokens("~siteCollection/Style Library/colorstatus.js"), init);
init();
});
Remember! You do have to apply the JSLink to both the View and the Form
use the fabulous WYSYWIG CSR Cisar editor
iCSR iSTATUS
Outras dicas
In SharePoint Online, you should be aware of the JavaScript/CSS customization is not allowed for the Modern Experience
list and libraries. Meanwhile, it's allowed for Classic Experience
.
In case, you are using Classic Experience
, you can apply conditional formatting via Jquery in Display form
based on a specific field value via the below code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" ></script>
<script>
$(document).ready(function(){
if ($('h3:contains("Status")').closest('td').next('td').text().indexOf('In progress') != -1)
{
$('h3:contains("Status")').closest('tr').css("background-color", "green");
}
else
{
$('h3:contains("Status")').closest('tr').css("background-color", "red");
}
});
</script>
For the detail steps, check CONDITIONAL FORMATING IN SHAREPOINT DISPLAY FORM VIA JQUERY