Call get model value attribute recursively to allow mutating form attribute in related models
This commit is contained in:
1 parent
7570f25d58
commit
752951ee5f
2 files changed
+33
-4
No files matched your search
+22
-4
@@ -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);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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);
|
||||
|
||||
Reference in new issue
Block a user