3069 Posts in 868 Topics by 650 members
|
Page:
1
|
Go to End | |
| Author | Topic: | 299 Views |
-
Get a Data Object based on filter from URL Params

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.
-
Re: Get a Data Object based on filter from URL Params

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;
}
| 299 Views | ||
|
Page:
1
|
Go to Top |

