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.

Template Questions /

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

Getting properties and calling methods is pure magic


Go to End


2146 Views

Avatar
Urug

Community Member, 4 Posts

4 August 2013 at 9:56pm

Edited: 04/08/2013 10:05pm

Consider following DataObject:

class News extends DataObject {
public static $db = Array(
'Title'  => 'Text',
'Date'   => 'Date',
)

public function getTitle() {
    return 'MyTitle';
}
  
public function getDate() {
  return date('j.n.',strtotime($this->getField('Date')));
}
}

now in the template:

<% loop $News %>
    <div class="news">
      <span class="date">$Date</span><a href="">$Title</a>
    </div>
<% end_loop%>

The overloaded method for field 'Title' is called corretly and string "MyTitle" is returned. On the other hand overloaded method for field 'Date' isn't called and the default getter is used instead, so the 'Date' si returned in DD-MM-YYYY format. Fortunately it can be fixed by changing $Date to $getDate in template.

Another similar problem is calling methods with parameters from template. If method is defined:

public function getSomething($param) {
  return 'Something with'.$param;
}

and $Something(Param) is used in template then [Warning] Missing argument 1 for SomeController::getSomething() is thrown. It's quite interesting to me, because it means that the right method is called, but the arguments are not passed. Again it can be fixed by changing $Something(Param) to $getSomething(Param).

I find this behavior inconsistent and confusing, is there any logic into it or am I missing something?