protected function PbfSynchronize::update in Permissions by field 8
Update entities ref. by a Pbf field synchronized when entity is updated.
Parameters
string $target_entity_type_id: The entity type id of targeted entity.
\Drupal\field\FieldConfigInterface $target_field: The Pbf field synchronized by on the referenced entity.
\Drupal\Core\Entity\EntityInterface $entity: The entity updated.
\Drupal\field\FieldConfigInterface $field: The Pbf field synchronized with on the entity.
1 call to PbfSynchronize::update()
- PbfSynchronize::synchronizeTarget in src/
PbfSynchronize.php - Launch the synchronization belong the operation done on the entity.
File
- src/
PbfSynchronize.php, line 225
Class
- PbfSynchronize
- Class PbfSynchronize.
Namespace
Drupal\pbfCode
protected function update($target_entity_type_id, FieldConfigInterface $target_field, EntityInterface $entity, FieldConfigInterface $field) {
$entity_original = isset($entity->original) ? $entity->original : $entity;
$target_field_name = $target_field
->getName();
$target_ids = $this
->getReferenceIds($entity, $field);
// Param added not used. We synchronize always the referenced entities.
$added = array_diff($this
->getReferenceIds($entity, $field), $this
->getReferenceIds($entity_original, $field));
// We synchronize all targeted entities.
if ($target_ids) {
$target_entities = $this->entityTypeManager
->getStorage($target_entity_type_id)
->loadMultiple($target_ids);
/** @var \Drupal\Core\Entity\FieldableEntityInterface $target_entity */
foreach ($target_entities as $target_entity) {
$ids_referenced_from_target = $this
->getReferenceIds($target_entity, $target_field);
if (!in_array($entity
->id(), $ids_referenced_from_target)) {
if ($target_entity
->hasField($target_field_name)) {
$target_entity->{$target_field_name}
->appendItem($entity
->id());
$target_entity
->save();
}
}
}
}
// If some entities referenced are removed, we removed the
// reference to the entity from these entities.
$deleted = array_diff($this
->getReferenceIds($entity_original, $field), $this
->getReferenceIds($entity, $field));
if ($deleted) {
$target_entities = $this->entityTypeManager
->getStorage($target_entity_type_id)
->loadMultiple($deleted);
foreach ($target_entities as $target_entity) {
$ids_referenced_from_target = $this
->getReferenceIds($target_entity, $target_field);
foreach ($ids_referenced_from_target as $delta => $reference) {
if ($reference == $entity
->id()) {
if ($target_entity
->hasField($target_field_name)) {
$target_entity
->get($target_field_name)
->removeItem($delta);
$target_entity
->save();
}
}
}
}
}
}