Jump to:

23355 Posts in 17873 Topics by 2862 members

General Questions

SilverStripe Forums » General Questions » URL field

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

Page: 1
Go to End
Author Topic: 1586 Views
  • Harley
    Avatar
    Community Member
    153 Posts

    URL field Link to this post

    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

  • Martijn
    Avatar
    Community Member
    271 Posts

    Re: URL field Link to this post

    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);
       }

  • Harley
    Avatar
    Community Member
    153 Posts

    Re: URL field Link to this post

    Thanks Martijn,

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

    Cheers

  • NathanBrauer
    Avatar
    Community Member
    11 Posts

    Re: URL field Link to this post

    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).

    1586 Views
Page: 1
Go to Top

Want to know more about the company that brought you SilverStripe? Then check out SilverStripe.com

Comments on this website? Please give feedback.