From 752951ee5f409fdfcd897a9d4545c84406465702 Mon Sep 17 00:00:00 2001 From: Adrian Gunawan Date: Wed, 19 Apr 2017 16:40:45 +1000 Subject: [PATCH] Call get model value attribute recursively to allow mutating form attribute in related models --- src/FormBuilder.php | 26 ++++++++++++++++++++++---- tests/FormAccessibleTest.php | 11 +++++++++++ 2 files changed, 33 insertions(+), 4 deletions(-) diff --git a/src/FormBuilder.php b/src/FormBuilder.php index dbe378c..e163852 100644 --- a/src/FormBuilder.php +++ b/src/FormBuilder.php @@ -1101,16 +1101,34 @@ class FormBuilder * Get the model value that should be assigned to the field. * * @param string $name + * @param mixed $model * * @return mixed */ - protected function getModelValueAttribute($name) + protected function getModelValueAttribute($name, $model = null) { - if (method_exists($this->model, 'getFormValue')) { - return $this->model->getFormValue($this->transformKey($name)); + if (!isset($model)) { + $model = $this->model; } - return data_get($this->model, $this->transformKey($name)); + $key = $this->transformKey($name); + + // Check for nested attribute + if (strpos($key, '.') !== false) { + $keys = explode('.', $key, 2); + + // get the first level + $_model = $this->getModelValueAttribute($keys[0], $model); + + // recursively get the next levels + return $this->getModelValueAttribute($keys[1], $_model); + } + + if (method_exists($model, 'getFormValue')) { + return $model->getFormValue($key); + } + + return data_get($model, $key); } /** diff --git a/tests/FormAccessibleTest.php b/tests/FormAccessibleTest.php index 9add106..8aa0cee 100644 --- a/tests/FormAccessibleTest.php +++ b/tests/FormAccessibleTest.php @@ -46,6 +46,17 @@ class FormAccessibleTest extends PHPUnit_Framework_TestCase $this->assertEquals($model->getFormValue('created_at'), $this->now->timestamp); } + public function testItCanMutateRelatedValuesForForms() + { + $model = new ModelThatUsesForms($this->modelData); + $relatedModel = new ModelThatUsesForms($this->modelData); + $model->setRelation('related', $relatedModel); + $this->formBuilder->setModel($model); + + $this->assertEquals($this->formBuilder->getValueAttribute('related[string]'), 'ponmlkjihgfedcba'); + $this->assertEquals($this->formBuilder->getValueAttribute('related[created_at]'), $this->now->timestamp); + } + public function testItCanGetRelatedValueForForms() { $model = new ModelThatUsesForms($this->modelData);