Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

We've moved the forum!

Please use forum.silverstripe.org for any new questions (announcement).
The forum archive will stick around, but will be read only.

You can also use our Slack channel or StackOverflow to ask for help.
Check out our community overview for more options to contribute.

Archive /

Our old forums are still available as a read-only archive.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo

Determining if a field is empty


Go to End


2 Posts   2890 Views

Avatar
UncleCheese

Forum Moderator, 4102 Posts

2 March 2008 at 5:36am

Edited: 02/03/2008 5:37am

I have a function that I add to most of my data types that looks like this:

function has($field)
{
   return !empty($this->{$field});
}

I use this to determine at the template level whether or not a specific field has any data, because sometimes the template will require different display logic if it doesn't. For instance:

<% if has(Email) %>
$Email
<% else %>
$Phone
<% end_if %>

My question is, first of all, is this a common practice, or is there an easier way? Secondly, how come when I had this function in my controller it was throwing a PHP error on the template syntax, but when I moved it to my data model, it worked fine? Aren't all template functions supposed to be in the controller? Weird.

Avatar
dio5

Community Member, 501 Posts

3 March 2008 at 5:41am

I just do

<% if Email %>
$Email
<% else %>
$Phone
<% end_if %>

without any function.