JSON column formatting with if/else in SharePoint?
-
07-02-2021 - |
Question
I would like to nest if conditions into SharePoint via JSON column format.
I have two fields, Date and Status. The status field contains 3 strings ("Done", "Pending", "New")
Example:
if ([$Date] < @NOW) {
if([$Status] == "Done") {
font color GREEN
} else {
font color RED
}
} elseif ([$Date] == @NOW) {
if([$Status] == "Job done") {
font color GREEN
} else {
font color RED
}
} else {
font color black;
}
And my Json code so far... (Only the first condition)
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
"elmType": "div",
"txtContent": "@currentField",
"style": {
"color": "=if([$DeadLine] <= @now + 86400000, '#FAFAFA', '#22ff00')"
}
}
Solution
Please note I haven't tested this code, but the concept is how to solve this. You will have to nest the IF statements.
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
"elmType": "div",
"txtContent": "@currentField",
"style": {
"color": "=if([$DeadLine] < @now, " +
"if([$Status] <= 'Done', '#00FF00', '#FF0000')," + /* TRUE CONDITION, DeadLine < Now */
"if([$DeadLine] == @now, " + /* False Condition Deadline is NOT less than Now: Second if statement */
"if([$Status] == 'Job done', '#00FF00' , '#FF0000' )," + /* Values for Status = Job done */
"'#000000'))" /* when all else fails, black */
}
}
Same code as a single line without comments
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/column-formatting.schema.json",
"elmType": "div",
"txtContent": "@currentField",
"style": {
"color": "=if([$DeadLine] < @now, if([$Status] <= 'Done', '#00FF00', '#FF0000'), if([$DeadLine] == @now, if([$Status] == 'Job done', '#00FF00' , '#FF0000' ),'#000000'))"
}
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange