public static function BulkUpdateFields::updateFields in Bulk Update Fields 8.2
Same name and namespace in other branches
- 8 src/BulkUpdateFields.php \Drupal\bulk_update_fields\BulkUpdateFields::updateFields()
File
- src/
BulkUpdateFields.php, line 70
Class
- BulkUpdateFields
- BulkUpdateFields.
Namespace
Drupal\bulk_update_fieldsCode
public static function updateFields($entity, $fields, &$context) {
$message = 'Updating Fields on ';
$langcode = $entity
->language()
->getId();
$entity = \Drupal::entityTypeManager()
->getStorage($entity
->getEntityTypeId())
->load($entity
->id());
$entity = $entity
->getTranslation($langcode);
$results_fields = [];
$update = FALSE;
foreach ($fields as $field_name => $field_value) {
if ($entity
->hasField($field_name)) {
$field_value = self::preprocessField($field_value);
$field_definition = $entity
->get($field_name)
->getFieldDefinition();
foreach ($field_value as $key => $value) {
if ($value == $field_name) {
continue;
}
// this is the case for field images for some reason
if (!is_array($value)) {
continue;
}
// some objects returned
$value = self::processField($value, $field_definition);
if (is_array($value) && isset($value['subform']) && isset($value['paragraph_type'])) {
$paragraph = Paragraph::create([
'type' => $value['paragraph_type'],
]);
foreach ($value['subform'] as $p_field_name => $p_field_value) {
if ($paragraph
->hasField($p_field_name)) {
$p_field_value = self::preprocessField($p_field_value);
$p_field_definition = $paragraph
->get($p_field_name)
->getFieldDefinition();
foreach ($p_field_value as $p_key => $p_value) {
if ($p_value == $p_field_name) {
continue;
}
// this is the case for field images for some reason
if (!is_array($p_value)) {
continue;
}
// some objects returned
$p_field_value[$p_key] = self::processField($p_value, $p_field_definition);
}
}
$paragraph
->get($p_field_name)
->setValue($p_field_value);
}
$paragraph
->save();
$value = $paragraph;
}
$field_value[$key] = $value;
}
$entity
->get($field_name)
->setValue($field_value);
$update = TRUE;
if (!in_array($field_name, $results_fields)) {
$results_fields[] = $field_name;
}
}
}
if ($update) {
// setNewRevision method exists on user but throws an error if called.
// TODO?: Do other entity types need revisions set?
if ($entity
->getEntityTypeId() == 'node' && method_exists($entity, 'setNewRevision')) {
$entity
->setNewRevision();
}
$entity
->save();
}
$context['results'][] = $entity
->id() . ' : ' . $entity
->label();
$context['message'] = $message . $entity
->label();
$context['results']['results_entities'][] = $entity
->id();
$context['results']['results_fields'] = $results_fields;
}