I am using dataobjectmanager with a many_many relationship (I can’t use manymanydataobjectmanager for this) between owner and car. Whenever a new car is created I iterate through all instances of owner and add it’s id to a linked table along with the new car ID.
My problem is that the code for doing this is within the onafterwrite method and is called twice. I’m not sure why. I’ve also noticed that for my three owners it is creating rows in the linked table oddly. The first two IDs will be in order then it will stick one. So it’ll be rows 1, 2 and 4 with no 3.
This is my onAfterWrite method
public function onAfterWrite() {
if(Permission::check('ADMIN')){
$Pages = DataObject::get('Owner');
foreach($Pages as $owner) {
DB::query("INSERT INTO Owner_Cars (OwnerID, CarID) VALUES ('". $owner->ID . "', '" . $this->ID . "')");
}
}
else {
echo "Failure";
return false;
}
return parent::onAfterWrite();
}
I’d appreciate any advice you could give me.
Thanks
The
onAfterWrite()method is probably called twice becausewrite()is called twice. The most common reason that this happens is that:In general, I don’t think you can rely on onAfterWrite() being called once: write() is supposed to be designed so that it can be called any old number of times and will only actually affect the database if there are changes to be made.
You would need need to make your code call the necessary DELETE, INSERT, and/or UPDATE statements to be compatible with this. You might, for example:
One other suggestion I would make, if you can, is to try out SilverStripe 3. SilverStripe 3’s GridField handles this kind of stuff more robustly out of the box and you might find it easier to build your app on that.