Skip to content

Commit

Permalink
FIX Handle fields with square brackets
Browse files Browse the repository at this point in the history
  • Loading branch information
dhensby committed Dec 13, 2016
1 parent 7ca876a commit 5248be9
Showing 1 changed file with 26 additions and 9 deletions.
35 changes: 26 additions & 9 deletions forms/Form.php
Expand Up @@ -1418,6 +1418,7 @@ public function loadDataFrom($data, $mergeStrategy = 0, $fieldList = null) {
if(is_object($data)) $this->record = $data;

// dont include fields without data
/** @var FormField[] $dataFields */
$dataFields = $this->Fields()->dataFields();
if($dataFields) foreach($dataFields as $field) {
$name = $field->getName();
Expand Down Expand Up @@ -1450,15 +1451,31 @@ public function loadDataFrom($data, $mergeStrategy = 0, $fieldList = null) {
$val = $data[$name];
}
// If field is in array-notation we need to access nested data
else if(strpos($name,'[')) {
// First encode data using PHP's method of converting nested arrays to form data
$flatData = urldecode(http_build_query($data));
// Then pull the value out from that flattened string
preg_match('/' . addcslashes($name,'[]') . '=([^&]*)/', $flatData, $matches);

if (isset($matches[1])) {
$exists = true;
$val = $matches[1];
else if(preg_match_all('/(.*)\[(.*)\]/U', $name, $matches)) {
//discard first match which is just the whole string
array_shift($matches);

$keys = array_pop($matches);
$name = array_shift($matches);
$name = array_shift($name);

if (array_key_exists($name, $data)) {
$tmpData = &$data[$name];
// drill down into the data array looking for the corresponding value
foreach ($keys as $arrayKey) {
if ($arrayKey !== '') {
$tmpData = &$tmpData[$arrayKey];
} else {
//empty square brackets means new array
if (is_array($tmpData)) {
$tmpData = array_shift($tmpData);
}
}
}
if ($tmpData) {
$val = $tmpData;
$exists = true;
}
}
}
}
Expand Down

0 comments on commit 5248be9

Please sign in to comment.