Skip to content

Instantly share code, notes, and snippets.

@chriscalip
Created August 21, 2019 20:26
Show Gist options
  • Save chriscalip/937531771c14434d41fed4f13d9facd8 to your computer and use it in GitHub Desktop.
Save chriscalip/937531771c14434d41fed4f13d9facd8 to your computer and use it in GitHub Desktop.
utility for updating a node or entity's field value. useful for bulk operations
<?php
/**
* Utility function either updates/inserts an entity field values; useful for bulk update situations to avoid node-save.
*
* @param string $entity_type eg. node, taxonomy_term, etc..
* @param string $bundle eg. asset, etc..
* @param string $entity_id
* @param string $field field name
* @param array $field_values indexed by delta, then an array of components. [0 => ['value' => 'County Name']]
*
* @throws Errors.
*/
function cduxx_set_entity_field_values($entity_type, $bundle, $entity_id, $field, $field_values) {
$map_column_vids = [
'node' => 'vid',
'taxonomy_term' => 'revision_id',
];
$map_column_id = [
'node' => 'nid',
'taxonomy_term' => 'tid',
];
$column_vid = $map_column_vids[$entity_type] ?? '';
$column_id = $map_column_id[$entity_type] ?? '';
if (empty($column_vid) || empty($column_id)) {
throw new \Exception('cduxx_set_entity_field_values input not supported entity-type');
}
$table_entity = $entity_type . '_field_data';
$table_entity_alias = substr($entity_type, 0, 1);
$table_entity_query = db_select($table_entity, $table_entity_alias);
$table_entity_query->addField($table_entity_alias, $column_vid);
$table_entity_query->condition($table_entity_alias . '.' . $column_id, $entity_id);
$revision_id = $table_entity_query->execute()->fetchField();
if (empty($revision_id)) {
throw new \Exception('cduxx_set_entity_field_values unable to triangulate revision-id from input');
}
$tables = [
// eg. node__field_address_json
$entity_type . '__'. $field,
// eg. node_revision__field_address_json
$entity_type . '_revision' . '__'. $field,
];
$column_keys = ['entity_id', 'revision_id', 'delta'];
$values_basic = [
'bundle' => $bundle,
'deleted' => 0,
'entity_id' => $entity_id,
'revision_id' => $revision_id,
'langcode' => 'en',
];
foreach ($tables as $table) {
foreach ($field_values as $delta => $components) {
$db_record = [];
$values_component = [];
foreach ($components as $component => $value) {
$db_column = $field . '_' . $component;
$values_component[$db_column] = $value;
}
$db_record = array_merge($values_basic, $values_component, ['delta' => $delta]);
$keys = [];
foreach ($column_keys as $column_key) {
$keys[$column_key] = $db_record[$column_key] ?? null;
}
try {
db_merge($table)->key($keys)->fields($db_record)->execute();
}
catch (\Exception $e) {
throw new \Exception($e->getMessage() . ', cduxx_set_entity_field_values bad db merge.');
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment