Skip to content

Commit

Permalink
Update Subform.php
Browse files Browse the repository at this point in the history
Added onCustomFieldsBeforeSave that allows the raw value to be modified before save, allowing showon attribute configurations.
  • Loading branch information
obuisard committed Sep 11, 2023
1 parent e105c62 commit 9d19185
Showing 1 changed file with 58 additions and 15 deletions.
73 changes: 58 additions & 15 deletions plugins/fields/subform/src/Extension/Subform.php
Original file line number Diff line number Diff line change
Expand Up @@ -226,21 +226,6 @@ public function onCustomFieldsPrepareField($context, $item, $field)
$row_subfields[$subfield->fieldname] = $subfield;
}

// Check conditions on fields (through the showon attribute)
// Done here to make sure all fields have a raw value

foreach ($row_subfields as $key => $subfield) {
$showOn = $subfield->params->get('showon', '');

if (empty($showOn)) {
continue;
}

if (!FieldsHelper::matchShowon($showOn, $row_subfields)) {
unset($row_subfields[$key]);
}
}

// Store all the sub fields of this row
$subform_rows[] = $row_subfields;
}
Expand Down Expand Up @@ -332,6 +317,64 @@ public function onCustomFieldsPrepareDom($field, \DOMElement $parent, Form $form
return $parent_field;
}

/**
* Modify the raw value of a field before saving it
*
* @param \stdClass $field The field
*
* @return void
*
* @since __DEPLOY_VERSION__
*/
public function onCustomFieldsBeforeSave($field)
{
if (empty($field->rawvalue)) {
return;
}

$decoded_value = json_decode($field->rawvalue, true);

if (!$decoded_value || !is_array($decoded_value)) {
return;
}

$subform_rows = [];

// Iterate over each row of the data
foreach ($decoded_value as $key => $row) {
$row_subfields = [];

// For each row, iterate over all the subfields
foreach ($this->getSubfieldsFromField($field) as $subfield) {
foreach ($row as $fieldId => $rawValue) {
if ($subfield->id === (int)str_replace('field', '', $fieldId)) {
$subfield->rawvalue = $rawValue;
$row_subfields[$subfield->fieldname] = $subfield;
}
}
}

$subform_rows[$key] = [];

// Check conditions on fields (through the showon attribute)
foreach ($row_subfields as $subfield) {
$showOn = $subfield->params->get('showon', '');

$subform_rows[$key]['field' . $subfield->id] = $subfield->rawvalue;

if (empty($showOn)) {
continue;
}

if (!FieldsHelper::matchShowon($showOn, $row_subfields)) {
unset($subform_rows[$key]['field' . $subfield->id]);
}
}
}

$field->rawvalue = json_encode($subform_rows);
}

/**
* Returns an array of all options configured for this field.
*
Expand Down

0 comments on commit 9d19185

Please sign in to comment.