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.

Data Model Questions /

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

Get a Data Object based on filter from URL Params


Go to End


2 Posts   2473 Views

Avatar
gwhizzl

Community Member, 3 Posts

18 September 2012 at 11:28am

Hi all,

I've currently got a basic member profiles system running, and I'm expanding it to respond to SEO friendly URLS e.g. ../profile/show/george instead of ../profile/show/1

"/profile" is the page, "/show" is the action and "/1" is obviously the ID.

The code for function show is:

function show()
{
if($Member = $this->getMemberByName()) //Use getMemberByID() for unfriendly URLS
{
$Data = array(
'Member' => $Member
);
return $this->Customise($Data);
}
else
{
return $this->httpError(404, 'Profile not be found');
}
}

And the function for getMemberByID is:

public function getMemberByID()
{
$Params = $this->getURLParams();

if(is_numeric($Params['ID']) && $Member = DataObject::get_by_id('Member', (int)$Params['ID']))
{
return $Member;
}
}

So I adapted it to filter the DataObject::get by a different field in the Member table, "URLSegment", which was applied through a separate DataObjectDecorator class.

My code for getMemberByName is:

function getMemberByName() {

$Params = $this->getURLParams();

if($Params && $Member = DataObject::get('Member', "`URLSegment` = '{$Params}'" ))
{
return $Member;
}
}

But it results in a 404.

I must be missing something in the DataObject query - any ideas?

Thanks in advance for help.

Avatar
gwhizzl

Community Member, 3 Posts

19 September 2012 at 5:49am

Ok I figured it out, here's what I did for anyone who's curious:

By removing the If statements in the show() function, I forced SS into bringing up an error. The error message revealed that the URL parameter was being passed to the DataObject::get query in the wrong format.

Here's the working code:

function getMemberByName() {

$Params = Director::URLParam('ID'); // Get the ID part of the URL (http://example.com/PAGE/Action/ID)
$URLSegment = Convert::raw2xml($Params); // Make sure it is in the correct format for a query. This also helps with SQL Injection I think

$Member = DataObject::get('Member', "\"Member\".\"URLSegment\" = '$URLSegment'" ); // I also cleaned up the query a little

return $Member;
}