From 0f733519bb19bec0be358e6ac27b9507d7886ce6 Mon Sep 17 00:00:00 2001 From: Leandro Gehlen Date: Tue, 14 Aug 2018 09:00:46 -0300 Subject: [PATCH] Added `useFormName` property (#37) * Added `useFormName` property --- src/SaveRelationsBehavior.php | 9 +++++---- tests/SaveRelationsBehaviorTest.php | 28 ++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/SaveRelationsBehavior.php b/src/SaveRelationsBehavior.php index 4accda8..9e2b3bd 100644 --- a/src/SaveRelationsBehavior.php +++ b/src/SaveRelationsBehavior.php @@ -27,6 +27,8 @@ class SaveRelationsBehavior extends Behavior { public $relations = []; + public $useFormName = true; + private $_relations = []; private $_oldRelationValue = []; // Store initial relations value private $_newRelationValue = []; // Store update relations value @@ -34,7 +36,6 @@ class SaveRelationsBehavior extends Behavior private $_relationsSaveStarted = false; private $_transaction; - private $_relationsScenario = []; private $_relationsExtraColumns = []; private $_relationsCascadeDelete = []; @@ -736,9 +737,9 @@ class SaveRelationsBehavior extends Behavior $modelClass = $relation->modelClass; /** @var ActiveQuery $relationalModel */ $relationalModel = new $modelClass; - $formName = $relationalModel->formName(); - if (array_key_exists($formName, $data)) { - $owner->{$relationName} = $data[$formName]; + $keyName = $this->useFormName ? $relationalModel->formName() : $relationName; + if (array_key_exists($keyName, $data)) { + $owner->{$relationName} = $data[$keyName]; } } } diff --git a/tests/SaveRelationsBehaviorTest.php b/tests/SaveRelationsBehaviorTest.php index 3c3c787..d830d9c 100644 --- a/tests/SaveRelationsBehaviorTest.php +++ b/tests/SaveRelationsBehaviorTest.php @@ -841,4 +841,32 @@ class SaveRelationsBehaviorTest extends \PHPUnit_Framework_TestCase $this->assertFalse($project->company->isNewRecord, 'Company record should be saved'); $this->assertFalse($project->company->users[0]->isNewRecord, 'Company Users records should be saved'); } + + + public function testLoadRelationNameAsDataKeyShouldSucceed() + { + $company = new Company([ + 'name' => 'NewSoft', + ]); + + $company->attachBehavior('saveRelations', [ + 'class' => SaveRelationsBehavior::className(), + 'relations' => ['users'], + 'useFormName' => false + ]); + + $data = [ + 'users' => [ + ['username' => "user1"], + ['username' => "user2"] + ] + ]; + + $company->loadRelations($data); + + $this->assertTrue($company->save(), 'Company could not be saved'); + $this->assertEquals('NewSoft', $company->name, 'Company\'s name is wrong'); + $this->assertEquals('user1', $company->users[0]->username); + $this->assertEquals('user2', $company->users[1]->username); + } }