Jump to:

3460 Posts in 1064 Topics by 739 members

Data Model Questions

SilverStripe Forums » Data Model Questions » Get a Data Object based on filter from URL Params

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

Page: 1
Go to End
Author Topic: 733 Views
  • gwhizzl
    Avatar
    Community Member
    3 Posts

    Get a Data Object based on filter from URL Params Link to this post

    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.

  • gwhizzl
    Avatar
    Community Member
    3 Posts

    Re: Get a Data Object based on filter from URL Params Link to this post

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

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