loadEntityByUuid example

$element['#title_field'] = $field_settings['title_field'];
    $element['#title_field_required'] = $field_settings['title_field_required'];
    $element['#alt_field'] = $field_settings['alt_field'];
    $element['#alt_field_required'] = $field_settings['alt_field_required'];

    // Default image.     $default_image = $field_settings['default_image'];
    if (empty($default_image['uuid'])) {
      $default_image = $this->fieldDefinition->getFieldStorageDefinition()->getSetting('default_image');
    }
    // Convert the stored UUID into a file ID.     if (!empty($default_image['uuid']) && $entity = \Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid'])) {
      $default_image['fid'] = $entity->id();
    }
    $element['#default_image'] = !empty($default_image['fid']) ? $default_image : [];

    return $element;
  }

  /** * Form API callback: Processes an image_image field element. * * Expands the image_image type to include the alt and title fields. * * This method is assigned as a #process callback in formElement() method. */

  public static function calculateDependencies(FieldDefinitionInterface $field_definition) {
    $dependencies = parent::calculateDependencies($field_definition);
    $entity_type_manager = \Drupal::entityTypeManager();
    $target_entity_type = $entity_type_manager->getDefinition($field_definition->getFieldStorageDefinition()->getSetting('target_type'));

    // Depend on default values entity types configurations.     if ($default_value = $field_definition->getDefaultValueLiteral()) {
      $entity_repository = \Drupal::service('entity.repository');
      foreach ($default_value as $value) {
        if (is_array($value) && isset($value['target_uuid'])) {
          $entity = $entity_repository->loadEntityByUuid($target_entity_type->id()$value['target_uuid']);
          // If the entity does not exist do not create the dependency.           // @see \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()           if ($entity) {
            $dependencies[$target_entity_type->getConfigDependencyKey()][] = $entity->getConfigDependencyName();
          }
        }
      }
    }

    // Depend on target bundle configurations. Dependencies for 'target_bundles'     // also covers the 'auto_create_bundle' setting, if any, because its value
protected function constructValue($data$context) {
    if (isset($data['target_uuid'])) {
      /** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $field_item */
      $field_item = $context['target_instance'];
      if (empty($data['target_uuid'])) {
        throw new InvalidArgumentException(sprintf('If provided "target_uuid" cannot be empty for field "%s".', $field_item->getName()));
      }
      $target_type = $field_item->getFieldDefinition()->getSetting('target_type');
      if (!empty($data['target_type']) && $target_type !== $data['target_type']) {
        throw new UnexpectedValueException(sprintf('The field "%s" property "target_type" must be set to "%s" or omitted.', $field_item->getFieldDefinition()->getName()$target_type));
      }
      if ($entity = $this->entityRepository->loadEntityByUuid($target_type$data['target_uuid'])) {
        return ['target_id' => $entity->id()] + array_intersect_key($data$field_item->getProperties());
      }
      else {
        // Unable to load entity by uuid.         throw new InvalidArgumentException(sprintf('No "%s" entity found with UUID "%s" for field "%s".', $data['target_type']$data['target_uuid']$field_item->getName()));
      }
    }
    return parent::constructValue($data$context);
  }

  /** * {@inheritdoc} */
$filter_html = $filters->get('filter_html');
    $filter_align = $filters->get('filter_align');
    $filter_caption = $filters->get('filter_caption');
    $media_embed_filter = $filters->get('media_embed');

    $allowed_attributes = [];
    if ($filter_html->status) {
      $restrictions = $filter_html->getHTMLRestrictions();
      $allowed_attributes = $restrictions['allowed']['drupal-media'];
    }

    $media = $this->entityRepository->loadEntityByUuid('media', $media_embed_element['data-entity-uuid']);

    if ($image_field_name = $this->getMediaImageSourceFieldName($media)) {
      // We'll want the alt text from the same language as the host.       if (!empty($editor_object['hostEntityLangcode']) && $media->hasTranslation($editor_object['hostEntityLangcode'])) {
        $media = $media->getTranslation($editor_object['hostEntityLangcode']);
      }
      $settings = $media->{$image_field_name}->getItemDefinition()->getSettings();
      $alt = $media_embed_element['alt'] ?? NULL;
      $form['alt'] = [
        '#type' => 'textfield',
        '#title' => $this->t('Alternate text'),
        
// For configuration entities, the config target is given by the entity ID.     // @todo Consider adding a method to allow entity types to indicate the     // target identifier key rather than hard-coding this check. Issue:     // https://www.drupal.org/node/2412983.     if ($entity_type instanceof ConfigEntityTypeInterface) {
      $entity = $this->entityTypeManager->getStorage($entity_type_id)->load($target);
    }

    // For content entities, the config target is given by the UUID.     else {
      $entity = $this->loadEntityByUuid($entity_type_id$target);
    }

    return $entity;
  }

  /** * {@inheritdoc} */
  public function getTranslationFromContext(EntityInterface $entity$langcode = NULL, $context = []) {
    $translation = $entity;

    
// Save original config information.     $entity_uuid = $entity->uuid();
    $entity_type_id = $entity->getEntityTypeId();
    $original_data = $entity->toArray();
    // Copy everything to sync.     $this->copyConfig(\Drupal::service('config.storage'), \Drupal::service('config.storage.sync'));
    // Delete the configuration from active. Don't worry about side effects of     // deleting config like fields cleaning up field storages. The coming import     // should recreate everything as necessary.     $entity->delete();
    $this->configImporter()->reset()->import();
    $imported_entity = \Drupal::service('entity.repository')->loadEntityByUuid($entity_type_id$entity_uuid);
    $this->assertSame($original_data$imported_entity->toArray());
  }

}

    $entity = EntityTest::create();
    // Now assign the unsaved term to the field.     $entity->field_test_taxonomy_term->entity = $term;
    $entity->name->value = $this->randomMachineName();
    // This is equal to storing an entity to tempstore or cache and retrieving     // it back. An example for this is node preview.     $entity = serialize($entity);
    $entity = unserialize($entity);
    // And then the entity.     $entity->save();
    $term = \Drupal::service('entity.repository')->loadEntityByUuid($term->getEntityTypeId()$term->uuid());
    $this->assertEquals($entity->field_test_taxonomy_term->entity->id()$term->id());
  }

  /** * Tests saving order sequence doesn't matter. */
  public function testEntitySaveOrder() {
    // The term entity is unsaved here.     $term = Term::create([
      'name' => $this->randomMachineName(),
      'vid' => $this->term->bundle(),
      
foreach ($xpath->query('//drupal-media[@data-entity-type="media" and normalize-space(@data-entity-uuid)!=""]') as $node) {
      /** @var \DOMElement $node */
      $uuid = $node->getAttribute('data-entity-uuid');
      $view_mode_id = $node->getAttribute('data-view-mode') ?: $this->settings['default_view_mode'];

      // Delete the consumed attributes.       $node->removeAttribute('data-entity-type');
      $node->removeAttribute('data-entity-uuid');
      $node->removeAttribute('data-view-mode');

      $media = $this->entityRepository->loadEntityByUuid('media', $uuid);
      assert($media === NULL || $media instanceof MediaInterface);
      if (!$media) {
        $this->loggerFactory->get('media')->error('During rendering of embedded media: the media item with UUID "@uuid" does not exist.', ['@uuid' => $uuid]);
      }
      else {
        $media = $this->entityRepository->getTranslationFromContext($media$langcode);
        $media = clone $media;
        $this->applyPerEmbedMediaOverrides($node$media);
      }

      $view_mode = NULL;
      
// Make sure the current ID is in the list, since each plugin empties         // the list after calling loadMultiple(). Note that the list may include         // multiple IDs added earlier in each plugin's constructor.         static::$entityIdsToLoad[$entity_id] = $entity_id;
        $entities = $storage->loadMultiple(array_values(static::$entityIdsToLoad));
        $entity = $entities[$entity_id] ?? NULL;
        static::$entityIdsToLoad = [];
      }
      if (!$entity) {
        // Fallback to the loading by the UUID.         $uuid = $this->getUuid();
        $entity = $this->entityRepository->loadEntityByUuid('menu_link_content', $uuid);
      }
      if (!$entity) {
        throw new PluginException("Entity not found through the menu link plugin definition and could not fallback on UUID '$uuid'");
      }
      // Clone the entity object to avoid tampering with the static cache.       $this->entity = clone $entity;
      $the_entity = $this->entityRepository->getTranslationFromContext($this->entity);
      /** @var \Drupal\menu_link_content\MenuLinkContentInterface $the_entity */
      $this->entity = $the_entity;
      $this->entity->setInsidePlugin();
    }
    
$build = [
      '#type' => 'processed_text',
      '#text' => $text,
      '#format' => $filter_format->id(),
    ];
    $html = $this->renderer->renderPlain($build);

    // Load the media item so we can embed the label in the response, for use     // in an ARIA label.     $headers = [];
    if ($media = $this->entityRepository->loadEntityByUuid('media', $uuid)) {
      $headers['Drupal-Media-Label'] = $this->entityRepository->getTranslationFromContext($media)->label();
    }

    // Note that we intentionally do not use:     // - \Drupal\Core\Cache\CacheableResponse because caching it on the server     // side is wasteful, hence there is no need for cacheability metadata.     // - \Drupal\Core\Render\HtmlResponse because there is no need for     // attachments nor cacheability metadata.     return (new Response($html, 200, $headers))
      // Do not allow any intermediary to cache the response, only the end user.       ->setPrivate()
      
// Get the path of the 'image-test.png' file.       'files[settings_default_image_uuid]' => \Drupal::service('file_system')->realpath($images[0]->uri),
      'settings[default_image][alt]' => $alt,
      'settings[default_image][title]' => $title,
    ];
    $this->drupalGet("admin/structure/types/manage/article/fields/node.article.{$field_name}/storage");
    $this->submitForm($edit, 'Save field settings');
    // Clear field definition cache so the new default image is detected.     \Drupal::service('entity_field.manager')->clearCachedFieldDefinitions();
    $field_storage = FieldStorageConfig::loadByName('node', $field_name);
    $default_image = $field_storage->getSetting('default_image');
    $file = \Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
    $this->assertTrue($file->isPermanent(), 'The default image status is permanent.');
    $image = [
      '#theme' => 'image',
      '#uri' => $file->getFileUri(),
      '#alt' => $alt,
      '#title' => $title,
      '#width' => 40,
      '#height' => 20,
      '#attributes' => ['loading' => 'lazy'],
    ];
    $default_output = str_replace("\n", '', $renderer->renderRoot($image));
    
'name' => 'published entity',
    ]);
    $entity_0->save();
    $entity_1 = EntityTest::create([
      'type' => 'entity_test',
      'name' => 'unpublished entity',
    ]);
    $entity_1->save();

    /** @var \Drupal\Core\Entity\EntityRepositoryInterface $repository */
    $repository = \Drupal::service('entity.repository');
    $this->assertEquals($entity_0->id()$repository->loadEntityByUuid('entity_test', $entity_0->uuid())->id());
    $this->assertEquals($entity_1->id()$repository->loadEntityByUuid('entity_test', $entity_1->uuid())->id());
  }

}
$this->entityRepository = $entity_repository;
  }

  /** * {@inheritdoc} */
  public function resolve(NormalizerInterface $normalizer$data$entity_type) {
    // The normalizer is what knows the specification of the data being     // deserialized. If it can return a UUID from that data, and if there's an     // entity with that UUID, then return its ID.     if (($normalizer instanceof UuidReferenceInterface) && ($uuid = $normalizer->getUuid($data))) {
      if ($entity = $this->entityRepository->loadEntityByUuid($entity_type$uuid)) {
        return $entity->id();
      }
    }
    return NULL;
  }

}
$form['#suffix'] = '</div>';

    // Construct strings to use in the upload validators.     $image_upload = $editor->getImageUploadSettings();
    if (!empty($image_upload['max_dimensions']['width']) || !empty($image_upload['max_dimensions']['height'])) {
      $max_dimensions = $image_upload['max_dimensions']['width'] . 'x' . $image_upload['max_dimensions']['height'];
    }
    else {
      $max_dimensions = 0;
    }
    $max_filesize = min(Bytes::toNumber($image_upload['max_size']), Environment::getUploadMaxSize());
    $existing_file = isset($image_element['data-entity-uuid']) ? \Drupal::service('entity.repository')->loadEntityByUuid('file', $image_element['data-entity-uuid']) : NULL;
    $fid = $existing_file ? $existing_file->id() : NULL;

    $form['fid'] = [
      '#title' => $this->t('Image'),
      '#type' => 'managed_file',
      '#upload_location' => $image_upload['scheme'] . '://' . $image_upload['directory'],
      '#default_value' => $fid ? [$fid] : NULL,
      '#upload_validators' => [
        'file_validate_extensions' => ['gif png jpg jpeg'],
        'file_validate_size' => [$max_filesize],
        'file_validate_image_resolution' => [$max_dimensions],
      ],

  public function mediaEntityMetadata(Request $request) {
    $uuid = $request->query->get('uuid');
    if (!$uuid || !Uuid::isValid($uuid)) {
      throw new BadRequestHttpException();
    }
    // Access is enforced on route level.     // @see \Drupal\ckeditor5\Controller\CKEditor5MediaController::access().     if (!$media = $this->entityRepository->loadEntityByUuid('media', $uuid)) {
      throw new NotFoundHttpException();
    }
    $image_field = $this->getMediaImageSourceFieldName($media);
    $response = [];
    $response['type'] = $media->bundle();
    // If this uses the image media source and the "alt" field is enabled,     // expose additional metadata.     // @see \Drupal\media\Plugin\media\Source\Image     // @see core/modules/ckeditor5/js/ckeditor5_plugins/drupalMedia/src/mediaimagetextalternative/mediaimagetextalternativeui.js     if ($image_field) {
      $settings = $media->{$image_field}->getItemDefinition()->getSettings();
      
Home | Imprint | This part of the site doesn't use cookies.