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.

General Questions /

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

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

detecting $has_one/$has_many changes

Go to End

3 Posts   1458 Views


Community Member, 19 Posts

27 June 2011 at 3:58pm


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?



Community Member, 56 Posts

27 June 2011 at 7:16pm

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() {
     $dos = DataObject::get( '<ClassName>', "MyFileID = $this->ID" );
     if( $dos ) {
          foreach( $dos as $do ) {
               $do->MyFileID = 0;


Community Member, 19 Posts

28 June 2011 at 11:43am

Awesome, didn't think of that. Thanks!