Swaiba is correct that doing a DataObject::get_by_id('Some_Object', $this->ID, false); will solve the problem.
This is because not all database calculated values (e.g. LastEdited) are not actually returned to the current instance of our object ($this) until AFTER the onAfterWrite has finished.
For example:
- $this is our current instance of object_x
- In the onBeforeWrite() function our DB table column which represents object_x HAS been updated and things like the LastEdited field have been set
- However, these DB generated values (I have not tested it to be sure but id imagine Created, LastEdited and ClassName are the values in question) are not returned to our instance of objext_x ($this) until AFTER the onAfterWrite has finished.
- Therefore they cannot be used/are old data when used in the onBeforeWrite()
Using
$obj = DataObject::get_by_id('Some_Object', $this->ID, false);
if($obj->SomeField == 'Some Value') {
// Do Stuff
}
rather than
if($this->SomeField == 'Some Value') {
// Do Stuff
}
solves the issue as it effectivly manually refreshes/updates your current instance of object_x
EDIT: Having implemented my own fix and still having issues with my returned LastEdited DATETIME I have realised something very interesting. Many of you may well know (as it is in the docs) that DataObject::get_one has a cached query option which defaults to true. DataObject::get_by_id() has absolutely no mention of the caching option in the docs anywhere I can see, but guess what it uses to do its lookup...a modified get_one()! Meaning that DataObject::get_by_id also uses a cached query by default! There is an optional third parmeter to overwrite this and do a fresh query, however it doesn't seem to be documented anywhere. See my line above. The third parameter was integral to my code working as using a cached query returned me outdated data!