Jump to:

3372 Posts in 998 Topics by 712 members

Data Model Questions

SilverStripe Forums » Data Model Questions » SS3 Checking DataObject in onBeforeWrite()

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

Page: 1
Go to End
Author Topic: 964 Views
  • zenmonkey
    Avatar
    Community Member
    524 Posts

    SS3 Checking DataObject in onBeforeWrite() Link to this post

    I'm going through Aram's DataObjectAsPage Tutorial, the module is isn't SS3 compatible so I figured I go through the tutorial and make the needed SS3 changes as I go. In the onBeforeWrite it checks for existing DataObjects with same URLSegment. However upgrading the query to the new ORM seems to cause a timeout (the function that times out seems to change with each execution).

    here is the existing code

    //Set URLSegment to be unique on write
    function onBeforeWrite()
    {
    // If there is no URLSegment set, generate one from Title
    if((!$this->URLSegment || $this->URLSegment == 'new-item') && $this->Name != 'New Item')
    {
    $this->URLSegment = SiteTree::generateURLSegment($this->Name);
    }
    else if($this->isChanged('URLSegment'))
    {
    // Make sure the URLSegment is valid for use in a URL
    $segment = preg_replace('/[^A-Za-z0-9]+/','-',$this->URLSegment);
    $segment = preg_replace('/-+/','-',$segment);

    // If after sanitising there is no URLSegment, give it a reasonable default
    if(!$segment) {
    $segment = "product-$this->ID";
    }
    $this->URLSegment = $segment;
    }

    // Ensure that this object has a non-conflicting URLSegment value.
    $count = 2;
    while($this->LookForExistingURLSegment($this->URLSegment))
    {
    $this->URLSegment = preg_replace('/-[0-9]+$/', null, $this->URLSegment) . '-' . $count;
    $count++;
    }

    parent::onBeforeWrite();
    }

    //Test whether the URLSegment exists already on another Product
    function LookForExistingURLSegment($URLSegment)
    {
       return (DataObject::get_one('ConsignmentItem', "URLSegment = '" . $URLSegment ."' AND ID != " . $this->ID));

    }

    It works as is, as soon as I try to modify the LookForExistingIRLSegment function to the new ORM it dies. I assume this is because of the execution pipeline (There is no ID yet). Just wondering how I can replicate this functionality without worrying about using depreciated functions

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