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.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, Ed, biapar, Willr, Ingo, swaiba

Get Object or 404


Go to End


5 Posts   6709 Views

Avatar
Mo

Community Member, 541 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, 541 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, 541 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, 5523 Posts

28 October 2010 at 12:16pm

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

$this->httpError(404);