public function onAfterWrite() { parent::onAfterWrite(); // If this is not attached to a group, find the first group prior to this // with no end attached $group = $this->Group(); if (!($group && $group->exists()) && $this->ParentID) { $group = EditableFieldGroup::get()->filter(array('ParentID' => $this->ParentID, 'Sort:LessThanOrEqual' => $this->Sort))->where('"EditableFieldGroup"."EndID" IS NULL OR "EditableFieldGroup"."EndID" = 0')->sort('"Sort" DESC')->first(); // When a group is found, attach it to this end if ($group) { $group->EndID = $this->ID; $group->write(); } } }