Save a field for every SiteTree item

25 views Asked by At

I have an extension that sets up search fields like this:

     public function onBeforeWrite(){                
       parent::onBeforeWrite();        
       $this->getOwner()->SearchContent = $this->collateSearchContent();
     }

Which works ok, except only on new or updated pages. I want to loop through the SiteTree and save the SearchContent for each.

In my task I do this:

     foreach (SiteTree::get() as $item) {
       $the_text = $item->collateSearchContent();   
       # Previously:  $item->getOwner()->SearchContent = $the_text;
       $item->SearchContent = $the_text;
       $item->write();
     }

I get the error:

 Caught exception: Object->__call(): the method 'collateSearchContent' does not exist on 'Page' 

So, nearly there. But it's not using the SiteTree object to find the method. How do I access the sitetree object?

1

There are 1 answers

5
Guy Sartorelli On

$this->getOwner() works in the first scenario because $this is an instance of Extension, and $this->getOwner() returns a SiteTree record.

In the second scenario, $item is the SiteTree record, so getOwner() isn't needed.

What's more, save() is not going to work, because that method doesn't exist on SiteTree (see API docs).

foreach (SiteTree::get() as $item) {
    $item->SearchContent = $item->collateSearchContent();
    $item->write();
}