Column Formatting to Show a Hyperlink or just Text Based on 3rd Field [duplicate]
Question
PrimaryLink is to display a hyperlink based on the other 2 fields
PrimaryName
PrimaryURL
PrimaryLink
JSON for Column Formatting
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "a",
"txtContent": "[$PrimaryName]",
"attributes": {
"target": "_blank",
"href": "[$PrimaryURL]"
}
}
So if I enter a PrimaryName and a PrimaryURL, it would display the PrimaryName as a hyperlink in PrimaryLink to what was set in PrimaryURL. If I only put a PrimaryName in, it still displays a hyperlink that goes to the /list/AllItems.aspx
Is there a way where if I don't populate PrimaryURL, that it can only display PrimaryName text and no hyperlink?
Tried this from a post recommended in comments, but it leaves the whole column empty.
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "a",
"txtContent": "[$PrimaryName]",
"attributes": {
"target": "_blank",
"href": "[$PrimaryURL]"
}
"style":{
"display": "=if([$PrimaryURL]!='', 'block', 'none !important')"
}
}
Solution
Use below JSON Code:
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "div",
"children": [
{
"elmType": "span",
"txtContent": "[$PrimaryName]",
"style": {
"display": "=if([$PrimaryURL] != '', 'none', 'block')"
}
},
{
"elmType": "a",
"txtContent": "[$PrimaryName]",
"attributes": {
"target": "_blank",
"href": "[$PrimaryURL]"
},
"style": {
"display": "=if([$PrimaryURL] != '', 'block', 'none')"
}
}
]
}
Output:
official documentation:
Update from Comments:
- In order to reference a column in JSON formatting it should be included in list view.
- If you are adding the URL in
PrimaryLink
column and then adding the JSON inPrimaryName
column then try below JSON:
{
"$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
"elmType": "div",
"children": [
{
"elmType": "span",
"txtContent": "@currentField",
"style": {
"display": "=if([$PrimaryLink] != '', 'none', 'block')"
}
},
{
"elmType": "a",
"txtContent": "@currentField",
"attributes": {
"target": "_blank",
"href": "[$PrimaryLink]"
},
"style": {
"display": "=if([$PrimaryLink] != '', 'block', 'none')"
}
}
]
}
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange