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

Get Object or 404


Reply


5 Posts   2358 Views

Avatar
Mo

Community Member, 510 Posts

16 October 2009 at 9:55pm

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

Avatar
Mo

Community Member, 510 Posts

28 October 2010 at 4:18am

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

Anyone got any ideas??

Mo

Avatar
Martijn

Community Member, 271 Posts

28 October 2010 at 5:11am

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

Avatar
Mo

Community Member, 510 Posts

28 October 2010 at 5:13am

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

Nice one Martijn!

Cheers

Mo

Avatar
Willr

Forum Moderator, 5513 Posts

28 October 2010 at 12:16pm

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

$this->httpError(404);