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

Stripping HTML tags from HTMLVarchar field


Go to End


3 Posts   4704 Views

Avatar
vwd

Community Member, 166 Posts

19 September 2014 at 7:38am

Edited: 19/09/2014 7:39am

Hi,

I notice that that the Text DB Field type has a NoHTML function. However there is nothing similar for the HTMLVarchar . Whilst I note that there is a workaround of using LimitWordCount() or LimitCharacters(), I'm wondering if there is anything else that can be done (particularly in the template) to strip HTML tags from a field.

Thanks.
VWD.

Avatar
Sygmoral

Community Member, 46 Posts

28 September 2014 at 9:29am

Edited: 28/09/2014 9:44am

I quite agree, I've needed that in the past as well!

I have just fixed it myself, but it requires a change in the core files. I have sent a pull request with this change to the team, see here:
https://github.com/silverstripe/silverstripe-framework/pull/3513

  • Go to framework/model/fieldtypes
  • Open StringField.php and Text.php
  • Look for the NoHTML function in the Text.php file, and move it to the StringField.php file
  • Also move the last line in the $casting array that concerns with NoHTML
  • Save both files
  • Since both Text and Varchar extend StringField, they now both have access to that function.

Avatar
kinglozzer

Community Member, 187 Posts

29 September 2014 at 10:40am

Edited: 29/09/2014 10:42am

Hi guys,

Until that pull request is merged, this could be solved with an extension - no need to edit core code.

mysite/_config/config.yml - there should be two spaces before ‘extensions’ and four spaces before the hyphen (the text formatting on here removes them!)

StringField:
  extensions:
    - StringFieldExtension

mysite/code/extensions/StringFieldExtension.php

<?php

class StringFieldExtension extends Extension {
	
	public function NoHTML() {
		return strip_tags($this->owner->value);
	}

}

You should then be able to use $MyField.NoHTML in your template. Hope this helps!