function yamlform_update_8009 in YAML Form 8
Issue #2712463: Provide Entity–attribute–value model for submissions. Populate 'yamlform_submission_data' table using batch process.
File
- includes/
yamlform.update.inc, line 172 - YAML Form module update hooks.
Code
function yamlform_update_8009(&$sandbox) {
// @see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Extension%21module.api.php/function/hook_update_N/8.1.x
// Loop through 100 form submission at at time.
$limit = 100;
if (!isset($sandbox['progress'])) {
$sandbox['progress'] = 0;
$sandbox['current_sid'] = 0;
$sandbox['max'] = \Drupal::database()
->query('SELECT COUNT(sid) FROM {yamlform_submission}')
->fetchField();
}
// @see \Drupal\yamlform\Entity\YamlFormSubmission::save().
$records = \Drupal::database()
->select('yamlform_submission', 's')
->fields('s', [
'sid',
'yamlform_id',
'data',
])
->condition('sid', $sandbox['current_sid'], '>')
->range(0, $limit)
->orderBy('sid', 'ASC')
->execute();
foreach ($records as $record) {
$data = Yaml::decode($record->data);
$yamlform_id = $record->yamlform_id;
$sid = $record->sid;
$rows = [];
$update_submission_record = FALSE;
foreach ($data as $name => &$item) {
if (is_array($item)) {
foreach ($item as $key => $value) {
// Remove target_id from saved entity_autocomplete fields.
if (is_array($value) && isset($value['target_id'])) {
$value = $value['target_id'];
$item[$key] = $value;
$update_submission_record = TRUE;
}
$rows[] = [
'yamlform_id' => $yamlform_id,
'sid' => $sid,
'name' => $name,
'delta' => (string) $key,
'value' => (string) $value,
];
}
}
else {
$rows[] = [
'yamlform_id' => $yamlform_id,
'sid' => $sid,
'name' => $name,
'delta' => '',
'value' => (string) $item,
];
}
}
// Delete existing submission data rows.
\Drupal::database()
->delete('yamlform_submission_data')
->condition('sid', $sid)
->execute();
// Insert new submission data rows.
$query = \Drupal::database()
->insert('yamlform_submission_data')
->fields([
'yamlform_id',
'sid',
'name',
'delta',
'value',
]);
foreach ($rows as $row) {
$query
->values($row);
}
$query
->execute();
// Update submission record.
if ($update_submission_record) {
\Drupal::database()
->update('yamlform_submission')
->fields([
'data' => Yaml::encode($data),
])
->condition('sid', $sid)
->execute();
}
$sandbox['progress']++;
$sandbox['current_sid'] = $sid;
}
$sandbox['#finished'] = $sandbox['progress'] >= $sandbox['max'] ? TRUE : $sandbox['progress'] / $sandbox['max'];
if ($sandbox['#finished']) {
return t("Populating the 'yamlform_submission_data' table is complete.");
}
}