invictus
invictus

Reputation: 825

Silverstripe 3.1 - onBefore/After Delete/Write doesn't work

I'm trying to execute a simple write command on onAfterWrite or before or onBeforeDelete. But it simply doesn't work.

Object1 -> here I want to execute the code. Has a $has_one relation(Item) to the Object2

public function onAfterWrite(){
    parent::onAfterWrite();

    $item = Object2::get()->byID($this->ItemID);
    $item->Title = 'test123';
    $item->write();
}

The same problem in each other onAfter/Before function. If got no error, or anything else.

Where could the mistake be?

Upvotes: 1

Views: 1018

Answers (1)

LiveSource
LiveSource

Reputation: 6409

If I'm understanding you correctly, you want to get and manipulate the Object2 record that is related via the has_one relationship to your Object1 record. Assuming you have declared your relationship in Object2 like this:

class Object2 extends DataObject{
  private static $has_one = array(
    'Object1' => 'Object1'
  );
  ...

Your onAfterWrite code in Object1 should look like

public function onAfterWrite(){
    parent::onAfterWrite();
    // use the find() method to look up the relation
    $item = Object2::get()->find('Object1ID', $this->ItemID);
    // check that the related item exists before editing
    if($item){
      $item->Title = 'test123';
      $item->write();
    }
}

Upvotes: 1

Related Questions