public function JsonapiHelper::updateRelationships in Entity Share 8
Same name and namespace in other branches
- 8.2 modules/entity_share_client/src/Service/JsonapiHelper.php \Drupal\entity_share_client\Service\JsonapiHelper::updateRelationships()
Create or update the entity reference field values of an entity.
TODO: Should this method be removed from the interface?
Parameters
\Drupal\Core\Entity\ContentEntityInterface $entity: The entity to update.
array $data: An array of data.
Overrides JsonapiHelperInterface::updateRelationships
1 call to JsonapiHelper::updateRelationships()
- JsonapiHelper::importEntityListData in modules/
entity_share_client/ src/ Service/ JsonapiHelper.php - Use data from the JSONAPI to import content.
File
- modules/
entity_share_client/ src/ Service/ JsonapiHelper.php, line 220
Class
- JsonapiHelper
- Class JsonapiHelper.
Namespace
Drupal\entity_share_client\ServiceCode
public function updateRelationships(ContentEntityInterface $entity, array $data) {
if (isset($data['relationships'])) {
$resource_type = $this->resourceTypeRepository
->get($entity
->getEntityTypeId(), $entity
->bundle());
// Reference fields.
foreach ($data['relationships'] as $field_name => $field_data) {
$field_name = $resource_type
->getInternalName($field_name);
$field = $entity
->get($field_name);
if ($this
->relationshipHandleable($field)) {
$field_values = [];
// Check that the field has data.
if ($field_data['data'] != NULL && isset($field_data['links']) && isset($field_data['links']['related'])) {
$referenced_entities_response = $this
->getHttpClient()
->get($field_data['links']['related'])
->getBody()
->getContents();
$referenced_entities_json = Json::decode($referenced_entities_response);
if (!isset($referenced_entities_json['errors'])) {
$referenced_entities_ids = $this
->importEntityListData($referenced_entities_json['data']);
$main_property = $field
->getItemDefinition()
->getMainPropertyName();
// Add field metadatas.
foreach ($this
->prepareData($field_data['data']) as $key => $field_value_data) {
// When dealing with taxonomy term entities which has a
// hierarchy, there is a virtual entity for the root. So
// $referenced_entities_ids[$key] may not exist.
// See https://www.drupal.org/node/2976856.
if (isset($referenced_entities_ids[$key])) {
$field_value = [
$main_property => $referenced_entities_ids[$key],
];
if (isset($field_value_data['meta'])) {
$field_value += $field_value_data['meta'];
}
// Allow to alter the field value with an event.
$event = new RelationshipFieldValueEvent($field, $field_value);
$this->eventDispatcher
->dispatch(RelationshipFieldValueEvent::EVENT_NAME, $event);
$field_values[] = $event
->getFieldValue();
}
}
}
}
$entity
->set($field_name, $field_values);
}
}
// Save the entity once all the references have been updated.
$entity
->save();
}
}