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

Adding text formating methods


Go to End


3 Posts   3026 Views

Avatar
JL

Community Member, 10 Posts

3 November 2010 at 7:44pm

What's the easiet way to add text formatting methods like URLEncode, Shorten to the fields, so that I can use $Title.URLEncode in the template, similar to $Title.XML. Thanks!

Avatar
swaiba

Forum Moderator, 1899 Posts

3 November 2010 at 10:39pm

how about - create a subclass of Text, MyText, and add the required methods to it, then change your $db from Text to MyText
note - totally untested but that is how I'd go about it. Maybe a decorator would work also...

Avatar
Lucas

Community Member, 10 Posts

13 March 2012 at 1:09pm

Add a decorator if it's just a method or two that you want to be available on all objects of the given type.

For example:

Create the decorator code (say in mysite/code/MyDateDecorator.php):

class MyDateDecorator extends DataObjectDecorator {
    public function Datetime() {
        return date('Y-m-d\TH:i:s', strtotime($this->owner->value));
    }
}

In mysite/_config.php, enable the extension:

   Object::add_extension('SS_Datetime', 'MyDateDecorator');

Then in your templates you can use it as below:

   <% control MyObject %>
        <h2>$Title</h2>
        <p>Created on <time datetime="$Created.Datetime">$Created.Nice</time></p>
   <% end_control %>