SharePoint JSON formatting document library columns

Copper Contributor

I'm using a JSON Formatting in one of the columns of a document library, and so far works just fine. I have only one issue. The documents inside the library are organized in folders, and those document have metadata (columns) generated when the documents are provided, but that's not the case for the folders themselves. For example. one of the columns is called Year Published (not created). I added another column called Years Since Published. I make some calculations using JSON formatting to calculate the years difference between that year, and the current year:

 

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "attributes": {
    "class": "=if(@currentField > 0,'', '')"
  },
  "children": [
    {
      "elmType": "span",
      "txtContent": "=if(floor((Number([$YearPublished]) != 0, Number(getYear(@now)) - Number([$YearPublished]), 'Year Published not provided')"
    }
  ]
}

 

The issue is that it display perfectly when I'm inside a folder, looking at the documents, but when I'm at the parent folder level, it shows NaN.

Annotation 2022-04-19 112151.jpg

 

I know this is a tricky question/issue, and probably more related to Views, but is there a way to at least show the column blank when I'm at the parent folder level? Ideally, it would be great to only show the metadata/columns when I'm inside the folder, but that's probably impossible to accomplish.

Thanks in advance.

 

1 Reply

@CubanGuy 

 

I think I figured it out. It won't hide the columns from view, but at least won't show the NaN. Just in case someone is in a similar situation. I used the Content Type column to do the trick:

 

{
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/column-formatting.schema.json",
  "elmType": "div",
  "attributes": {
    "class": "=if(@currentField > 0,'', '')"
  },
  "children": [
    {
      "elmType": "span",
      "txtContent": "=if([$ContentType] != 'Folder', if(Number([$YearPublished]) != 0, floor(Number(getYear(@now)) - Number([$YearPublished])), 'Year Published not provided'), '')"
    }
  ]
}