Detecting if a field exists in a page template

Tatyana Nemchenko asked on January 19, 2018 22:37

I have the following logic in a Master page. The Data Type for the field is Boolean(Yes/No). The logic works great for pages with that field but throws an error when that field isn't there. Is there a way to detect if the field exists and is true.

<% if(DocumentContext.CurrentDocument.GetValue("isOverview").ToString() == "True") { %>

Recent Answers


Trevor Fayas answered on January 20, 2018 00:48

That's because GetValue("isOverview") will be null in other pages.

Use this:

<% if(DocumentContext.CurrentDocument.GetValue("isOverview") != null ? DocumentContext.CurrentDocument.GetValue("isOverview").ToString() == "True" : false) { %>

or even better:

<% if(CMS.Helpers.ValidationHelper.GetBoolean(DocumentContext.CurrentDocument.GetValue("isOverview"), false)) { %>

1 votesVote for this answer Mark as a Correct answer

Peter Mogilnitski answered on January 22, 2018 17:01 (last edited on December 10, 2019 02:31)

  1. If this column allows null values then It might be complicated I would look into {%CurrentDocument.TypeInfo. |(identity)GlobalAdministrator%} to see if there is something there to check the existence of column.

  2. the other way would be to create a custom macro where you can catch an exception when you try to access property of document i.e CurrentDocument.GetValue("isOverview"):

bool isOverview; try { isOverview = (bool)CurrentDocument.GetValue("isOverview"); } catch(Exception exception) { // column does not exist }

Ideally you don't want extra sql query to make sure if column is there.

3rd way I would hard code the list of document types that have this custom column and simply check in macro if your current document type (class) is in this list then access column.

0 votesVote for this answer Mark as a Correct answer

Peter Mogilnitski answered on January 22, 2018 17:48 (last edited on December 10, 2019 02:31)

Actually it is kinda ugly but you can do it with 2 line macro:

{%isColumnExist = CurrentDocument.isOverview|(identity)GlobalAdministrator%}

The only issue is that if isOverview exists it must have a value different from null. isColumnExist is null after the 1st macro if it is failing. In the second macro you check if it has any value.

P.S. Still the idea is not to have a SQL query to check column existence in the document type.

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.