Browse Source

Added `useFormName` property (#37)

* Added `useFormName` property
tags/1.6.0
Leandro Gehlen 6 years ago committed by Alban Jubert
parent
commit
0f733519bb
  1. 9
      src/SaveRelationsBehavior.php
  2. 28
      tests/SaveRelationsBehaviorTest.php

9
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];
}
}
}

28
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);
}
}

Loading…
Cancel
Save