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

URL field


Go to End
Reply


4 Posts   2209 Views

Avatar
Harley

Community Member, 162 Posts

25 September 2010 at 6:42am

Hello everyone,

I'm currently working on a site that has a ComplexTableField with a field for adding links. What I would like is for people to put a url in here and for it to add in the http:// prefix if it hasn't already been entered.

Is there a specific field type for the back end that will do this for me?

Thanks

Avatar
Martijn

Community Member, 271 Posts

25 September 2010 at 7:44pm

public function onBeforeWrite() {
		parent::onBeforeWrite();
		
		$url = $this->Website;
		if($url) {
			if(substr($url, 0, 8) != 'https://') {
				if(substr($url, 0, 7) != 'http://') {
					$url = $this->Website = 'http://' . $url;
				}
			}
		}
		
		$this->Website = strtolower($url);
	}

Avatar
Harley

Community Member, 162 Posts

25 September 2010 at 10:38pm

Thanks Martijn,

I thought there may have been a specific field type that would deal with it but your replacement is perfect!

Cheers

Avatar
NathanBrauer

Community Member, 11 Posts

9 January 2014 at 9:58am

Edited: 20/04/2014 3:27am

This may be more useful:

	function setWebsite($URL) {
		if (!$URL || !trim($URL)) return $this->setField('Website','');

		if (!preg_match('/^https?:\/\//i',$URL)) {
			$URL = 'http://'.$URL;
		}
		return $this->setField('Website',$URL);
	}

This will be processed any time $Object->Website = "something" occurs.

I purposefully didn't include strtolower. URLs ARE case sensitive (though domains and protocols are not).