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.

Template Questions

string length after trim in conditional


Go to End
Reply

14 Posts   3284 Views

Avatar
MarcelKlomp

29 December 2010 at 11:36pm Community Member, 5 Posts

When using <% if SomeField %> conditional fields with only spaces in them are displayed as well. Is there a way to do something like if(trim(strlen($var))>0) in template conditionals?

I'm aware I could do this with a custom function in my php file but then I'd have to check all fields individually which seems rather elaborate.

My apologies in advance by the way if this is something documented or already previously answered.

Avatar
Willr

1 January 2011 at 6:20pm Forum Moderator, 5511 Posts

Is there a way to do something like if(trim(strlen($var))>0) in template conditionals?

No, you will need a method in your controller to do this logic. You could have a function called StringExists($string) and then you have a reusable <% if StringExists(FieldName) %>

Avatar
MarcelKlomp

3 January 2011 at 1:37am Community Member, 5 Posts

Thanks Willr, sweet and simple! Why didn't I think of that?

Avatar
spankmaster79

16 January 2011 at 6:44am Community Member, 46 Posts

hi,

could you please tell me why this doesn't work for me? The field in the database is Varchar field. And my function looks like this:

/**
    * check if a string exists
    * @param unknown_type $varname
    */
   public function StringExists($string) {
      if(trim(strlen($string))>0) {
         return true;
      }
      return false;
   }

I don't even see the function getting called. In Page.ss I have:

<% if StringExists(URL) %>
<a href="$URL" class="ext" >$Titel</a>
<% end_if %>

Avatar
Pigeon

16 January 2011 at 1:25pm Community Member, 243 Posts

You can't pass variables in the template, only literal strings. If you want to check it on a property of the current object, then your controller method should be like this:

public function StringExists() {
if(trim(strlen($this->URL))>0) {
return true;
}
return false;
}

As a side note, i'm slightly baffled as to why anyone would trim() and strlen() as strlen() will return an integer :S

Avatar
swaiba

16 January 2011 at 9:56pm Forum Moderator, 1796 Posts

@Pigeon - to make sure if someone put a single space that the string is counted as blank?

Avatar
martimiz

17 January 2011 at 12:33am Forum Moderator, 1095 Posts

:-)

if(strlen(trim($this->URL))>0) {...

Avatar
MarcelKlomp

17 January 2011 at 12:50am Community Member, 5 Posts

@Pigeon yes, you're right of course. @swaiba answers the why, and @martimiz answers the how. My bad for putting it the wrong way around initially. Trust me however that in the actual code I have it in the right order.

Go to Top