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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Creating Custom Codes (find/replace text)


Reply


6 Posts   1416 Views

Avatar
DeklinKelly

Community Member, 197 Posts

11 May 2009 at 9:38pm

I would like to replace all instances of [c] with © on the website but not in the admin area. So in the admin there should be a textarea with [c] but on the public site © will be displayed instead.

<?php

class SpecialPage extends Page {
static $db = array(
'Text1' => 'Text',
);

static $has_one = array(
);
   
function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab("Root.Content.Content", new TextareaField('Text1', 'Text'));
return $fields;
}
}

class SpecialPage_Controller extends Page_Controller {
   
}

?>

Avatar
banal

Community Member, 901 Posts

11 May 2009 at 11:43pm

To make this happen, you could implement your own TextParser (http://api.silverstripe.com/sapphire/misc/TextParser.html)
That way, it would be usable for all fields.

Here's how I would do it:
Create a new file named "CopyParser.php" in mysite/code/parsers. The file should contain the following code:

<?php
class CopyParser extends TextParser
{
   function parse(){
      return str_replace('[c]', '&copy;', $this->content);
   }
}

Then in your template you should be able to call

$Content.Parse(CopyParser)

Avatar
DeklinKelly

Community Member, 197 Posts

12 May 2009 at 5:09am

Thanks, banal. That was easy to implement!

Avatar
DeklinKelly

Community Member, 197 Posts

12 May 2009 at 10:41pm

This does not work if I change the db type to Varchar. It only works if the db type is text. How can I get this to work for Varchar fields?

'Heading1' => 'Varchar',

Avatar
banal

Community Member, 901 Posts

12 May 2009 at 11:40pm

Yes, that's because the Parse method is a member of the "Text" class. Varchar is another class and doesn't inherit from Text (see core/model/fieldtypes). Maybe you could create your own Varchar subclass (or decorator) with the functionality you need. Or you just set that field to "Text" instead of Varchar (you could still use single-line textfields in the CMS).

Depends on how much programming you're planning to do, to get that feature you want :)

Avatar
Ben Gribaudo

Community Member, 181 Posts

15 May 2009 at 6:44am

You could also override Content() in your page class so that it performs the desired substitution. Content() is called during output rendering but not when the CMS admin interface is loaded.