Skip to content

Commit

Permalink
NEW: Support dot syntax in form field names
Browse files Browse the repository at this point in the history
 
This change adds support for these in a few places.

 - Form::saveInto($record)
 - Form::loadDataForm($record)
 - Form::loadDataForm($_POST)

Fixes #9163
  • Loading branch information
Sam Minnee authored and chillu committed May 20, 2021
1 parent 713a0b4 commit 02fb7c3
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 10 deletions.
29 changes: 21 additions & 8 deletions src/Forms/Form.php
Original file line number Diff line number Diff line change
Expand Up @@ -1462,16 +1462,29 @@ public function loadDataFrom($data, $mergeStrategy = 0, $fieldList = null)
$val = null;

if (is_object($data)) {
$exists = (
isset($data->$name) ||
$data->hasMethod($name) ||
($data->hasMethod('hasField') && $data->hasField($name))
);

if ($exists) {
$val = $data->__get($name);
// Allow dot-syntax traversal of has-one relations fields
if (strpos($name, '.') !== false && $data->hasMethod('relField')) {
$val = $data->relField($name);
$exists = true;

// Regular ViewableData access
} else {
$exists = (
isset($data->$name) ||
$data->hasMethod($name) ||
($data->hasMethod('hasField') && $data->hasField($name))
);

if ($exists) {
$val = $data->__get($name);
}
}

// Regular array access. Note that dot-syntax not supported here
} elseif (is_array($data)) {
// PHP turns the '.'s in POST vars into '_'s
$name = str_replace('.', '_', $name);

if (array_key_exists($name, $data)) {
$exists = true;
$val = $data[$name];
Expand Down
14 changes: 12 additions & 2 deletions src/Forms/FormField.php
Original file line number Diff line number Diff line change
Expand Up @@ -469,8 +469,18 @@ public function Value()
*/
public function saveInto(DataObjectInterface $record)
{
if ($this->name) {
$record->setCastedField($this->name, $this->dataValue());
$component = $record;
$fieldName = $this->name;

// Allow for dot syntax
if (($pos = strrpos($this->name, '.')) !== false) {
$relation = substr($this->name, 0, $pos);
$fieldName = substr($this->name, $pos + 1);
$component = $record->relObject($relation);
}

if ($fieldName) {
$component->setCastedField($fieldName, $this->dataValue());
}
}

Expand Down

0 comments on commit 02fb7c3

Please sign in to comment.