diff --git a/src/ORM/DataObject.php b/src/ORM/DataObject.php index 30d2c426d..8a8069bf1 100644 --- a/src/ORM/DataObject.php +++ b/src/ORM/DataObject.php @@ -2370,8 +2370,8 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity */ public function getField($field) { - // If we already have an object in $this->record, then we should just return that - if (isset($this->record[$field]) && is_object($this->record[$field])) { + // If we already have a value in $this->record, then we should just return that + if (isset($this->record[$field])) { return $this->record[$field]; } @@ -2591,13 +2591,15 @@ class DataObject extends ViewableData implements DataObjectInterface, i18nEntity // Support component assignent via field setter $schema = static::getSchema(); if ($schema->unaryComponent(static::class, $fieldName)) { + unset($this->components[$fieldName]); // Assign component directly if (is_null($val) || $val instanceof DataObject) { return $this->setComponent($fieldName, $val); } // Assign by ID instead of object - unset($this->components[$fieldName]); - $fieldName .= 'ID'; + if (is_numeric($val)) { + $fieldName .= 'ID'; + } } // Situation 1: Passing an DBField diff --git a/tests/php/ORM/DataObjectTest.php b/tests/php/ORM/DataObjectTest.php index ab37a6e80..606075f5b 100644 --- a/tests/php/ORM/DataObjectTest.php +++ b/tests/php/ORM/DataObjectTest.php @@ -673,6 +673,31 @@ class DataObjectTest extends SapphireTest ); } + /** + * Test has_one used as field getter/setter + */ + public function testHasOneAsField() + { + /** @var DataObjectTest\Team $team1 */ + $team1 = $this->objFromFixture(DataObjectTest\Team::class, 'team1'); + $captain1 = $this->objFromFixture(DataObjectTest\Player::class, 'captain1'); + $captain2 = $this->objFromFixture(DataObjectTest\Player::class, 'captain2'); + + // Setter: By RelationID + $team1->CaptainID = $captain1->ID; + $team1->write(); + $this->assertEquals($captain1->ID, $team1->Captain->ID); + + // Setter: New object + $team1->Captain = $captain2; + $team1->write(); + $this->assertEquals($captain2->ID, $team1->Captain->ID); + + // Setter: Custom data (required by DataDifferencer) + $team1->Captain = DBField::create_field('HTMLFragment', '
No captain
'); + $this->assertEquals('No captain
', $team1->Captain); + } + /** * @todo Extend type change tests (e.g. '0'==NULL) */