diff --git a/src/FormBuilder.php b/src/FormBuilder.php index 95f620a..cff42d5 100644 --- a/src/FormBuilder.php +++ b/src/FormBuilder.php @@ -1108,16 +1108,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);