diff --git a/CHANGELOG.md b/CHANGELOG.md index 093e434..6fa54a9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,9 @@ # Yii2 Active Record Save Relations Behavior Change Log +## [1.4.1] +### Fixed +- Bug #24: Fix a regression introduced in 1.4.0 release where validation of hasOne relations was not triggered. (thx @dabkhazi) + ## [1.4.0] ### Fixed - Bug #25: Fix for Yii 2.0.14 compatibility. Has many relations were not saved. (thx @SanChes-tanker) diff --git a/src/SaveRelationsBehavior.php b/src/SaveRelationsBehavior.php index 53a5c8c..0612c8a 100644 --- a/src/SaveRelationsBehavior.php +++ b/src/SaveRelationsBehavior.php @@ -291,10 +291,12 @@ class SaveRelationsBehavior extends Behavior $relationModel = $model->{$relationName}; $p1 = $model->isPrimaryKey(array_keys($relation->link)); $p2 = $relationModel::isPrimaryKey(array_values($relation->link)); + $pettyRelationName = Inflector::camel2words($relationName, true); if ($relationModel->getIsNewRecord() && $p1 && !$p2) { // Save Has one relation new record - $pettyRelationName = Inflector::camel2words($relationName, true); $this->saveModelRecord($model->{$relationName}, $event, $pettyRelationName, $relationName); + } else { + $this->validateRelationModel($pettyRelationName, $relationName, $relationModel, $event); } } else { // Save Has many relations new records diff --git a/tests/SaveRelationsBehaviorTest.php b/tests/SaveRelationsBehaviorTest.php index 9641440..f084c7c 100644 --- a/tests/SaveRelationsBehaviorTest.php +++ b/tests/SaveRelationsBehaviorTest.php @@ -11,6 +11,7 @@ use tests\models\Project; use tests\models\ProjectNoTransactions; use tests\models\Tag; use tests\models\User; +use tests\models\UserProfile; use Yii; use yii\base\Model; use yii\db\Migration; @@ -710,4 +711,18 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase $this->assertEquals($project->company->name, "Tutu"); $this->assertEquals($project->company->users[0]->username, "Someone Else"); } + + public function testHasOneRelationShouldTriggerOnBeforeValidateEvent() + { + $user = new User(); + $user->setAttributes([ + 'username' => 'Larry Page', + 'company_id' => 3 + ]); + $user->userProfile = new UserProfile(); + $this->assertFalse($user->save(), 'User should not be saved'); + $this->assertCount(1, $user->userProfile->getErrors()); + $user->userProfile->bio = 'Lawrence Edward Page (born March 26, 1973) is an American computer scientist and Internet entrepreneur who co-founded Google with Sergey Brin.'; + $this->assertTrue($user->save(), 'User could not be saved'); + } }