Jump to:

23367 Posts in 18143 Topics by 2863 members

General Questions

SilverStripe Forums » General Questions » Get Object or 404

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: 2130 Views
  • Mo
    Avatar
    Community Member
    504 Posts

    Get Object or 404 Link to this post

    Hi All,

    I was just wondering if SIlverstripe had anything similar to the get_object_or_404 method in django?

    Basically I want to return a 404 error if dataobject::get returns an empty object set.

    Any help greatly appreciated .

    Mo

  • Mo
    Avatar
    Community Member
    504 Posts

    Re: Get Object or 404 Link to this post

    Wow a whole year and I still haven't found an answer to this.

    Anyone got any ideas??

    Mo

  • Martijn
    Avatar
    Community Member
    271 Posts

    Re: Get Object or 404 Link to this post

    I use something like this to return a 404:

    function Article(){   
          $params = $this->getURLParams();
          if($url_segment = $params['ID']){
             $article = DataObject::get_one('Article',"URLSegment = '".(string)$url_segment."'");
             if(!$article && !Director::redirected_to()){
                $errorPage = DataObject::get_one('ErrorPage');
                Director::redirect($errorPage->Link(),404);   
             } else{
                return $article;   
             }
          }
       }

  • Mo
    Avatar
    Community Member
    504 Posts

    Re: Get Object or 404 Link to this post

    Hmm, yea, thats an idea. Hadn't thought of that.

    Nice one Martijn!

    Cheers

    Mo

  • Willr
    Avatar
    Forum Moderator
    5489 Posts

    Re: Get Object or 404 Link to this post

    Or to return a 404 you can do the following in a controller.

    $this->httpError(404);

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