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

SS3 Checking DataObject in onBeforeWrite()


Go to End


3443 Views

Avatar
zenmonkey

Community Member, 545 Posts

27 June 2012 at 3:07am

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