Jump to:

23355 Posts in 17838 Topics by 2862 members

General Questions

SilverStripe Forums » General Questions » detecting $has_one/$has_many changes

General questions about getting started with SilverStripe that don't fit in any of the categories above.

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

Page: 1
Go to End
Author Topic: 1022 Views
  • Room9
    Avatar
    Community Member
    19 Posts

    detecting $has_one/$has_many changes Link to this post

    Hi,

    I can't seem to find a way to detect relationship additions/changes in onAfterWrite(). E.g. I have a DataObject which $has_one MyFile. When I test onAfterWrite() and look for $this->MyFileID after adding an object it shows the new ID. This is great, but I remove the MyFile, the ID doesn't revert to 0. Likewise $this->MyFile()->exists(), $this->MyFile() and $this->MyFile->ID all return old data, only after saving for second time do I get the current values. Furthermore, $this->getChangedFields() behaves like MyFileID, showing only addtions, not deletions.

    Is this normal behaviour or do I have something wrong and the relation ID should be resetting to 0?

    r9

  • cuSSter
    Avatar
    Community Member
    56 Posts

    Re: detecting $has_one/$has_many changes Link to this post

    What happens is the MyFile object was removed from the database, but the fields of the object that have this has_one relationship to MyFile wasn't updated. In your MyFile class, you need to declare a onBeforeDelete() function which updates the MyFileID field to zero.

    function onBeforeDelete() {
    parent::onBeforeDelete();
    $dos = DataObject::get( '<ClassName>', "MyFileID = $this->ID" );
    if( $dos ) {
    foreach( $dos as $do ) {
    $do->MyFileID = 0;
    $do->write();
    }
    }
    }

  • Room9
    Avatar
    Community Member
    19 Posts

    Re: detecting $has_one/$has_many changes Link to this post

    Awesome, didn't think of that. Thanks!

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