From 786a8332374cc291af10dfd1a934c6902348e715 Mon Sep 17 00:00:00 2001 From: Sam Georges Date: Sun, 18 May 2014 15:39:12 +1000 Subject: [PATCH] Form Controller now pushes values to relations --- modules/backend/behaviors/FormController.php | 35 ++++++++++++++------ 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/modules/backend/behaviors/FormController.php b/modules/backend/behaviors/FormController.php index 4e23e276a..0c48d5fb8 100644 --- a/modules/backend/behaviors/FormController.php +++ b/modules/backend/behaviors/FormController.php @@ -130,11 +130,8 @@ class FormController extends ControllerBehavior $this->controller->formBeforeSave($model); $this->controller->formBeforeCreateSave($model); - $saveData = $this->formWidget->getSaveData(); - foreach ($saveData as $attribute => $value) { - $model->{$attribute} = $value; - } - $model->save(null, $this->formWidget->getSessionKey()); + $this->setModelAttributes($model, $this->formWidget->getSaveData()); + $model->push($this->formWidget->getSessionKey()); $this->controller->formAfterSave($model); @@ -182,11 +179,8 @@ class FormController extends ControllerBehavior $this->controller->formBeforeSave($model); $this->controller->formBeforeEditSave($model); - $saveData = $this->formWidget->getSaveData(); - foreach ($saveData as $attribute => $value) { - $model->{$attribute} = $value; - } - $model->save(null, $this->formWidget->getSessionKey()); + $this->setModelAttributes($model, $this->formWidget->getSaveData()); + $model->push($this->formWidget->getSessionKey()); $this->controller->formAfterSave($model); @@ -519,4 +513,25 @@ class FormController extends ControllerBehavior */ public function formExtendQuery($query) {} + // + // Internals + // + + /** + * Sets a data collection to a model attributes, relations will also be set. + * @param array $saveData Data to save. + * @param Model $model Model to save to + * @return void + */ + private function setModelAttributes($model, $saveData) + { + $singularTypes = ['belongsTo', 'hasOne', 'morphOne']; + foreach ($saveData as $attribute => $value) { + if ($model->hasRelation($attribute) && in_array($model->getRelationType($attribute), $singularTypes)) + $this->setModelAttributes($model->{$attribute}, $value); + else + $model->{$attribute} = $value; + } + } + } \ No newline at end of file