getSourceFieldDefinition example


class TestWithHiddenSourceField extends Test {

  /** * {@inheritdoc} */
  public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
    $display->removeComponent($this->getSourceFieldDefinition($type)->getName());
  }

  /** * {@inheritdoc} */
  public function prepareFormDisplay(MediaTypeInterface $type, EntityFormDisplayInterface $display) {
    $display->removeComponent($this->getSourceFieldDefinition($type)->getName());
  }

  /** * {@inheritdoc} */
'bundle' => $this->testMediaType->id(),
      'name' => 'Unnamed',
      'field_media_test' => 'Nation of sheep, ruled by wolves, owned by pigs.',
    ]);
    $media->save();

    $this->assertNotInstanceOf(MediaInterface::class, Media::load(rand(1000, 9999)));

    $this->assertInstanceOf(MediaInterface::class, Media::load($media->id()));
    $this->assertSame($this->testMediaType->id()$media->bundle(), 'The media item was not created with the correct type.');
    $this->assertSame('Unnamed', $media->getName(), 'The media item was not created with the correct name.');
    $source_field_name = $media->bundle->entity->getSource()->getSourceFieldDefinition($media->bundle->entity)->getName();
    $this->assertSame('Nation of sheep, ruled by wolves, owned by pigs.', $media->get($source_field_name)->value, 'Source returns incorrect source field value.');
  }

}
/** @var \Drupal\media\MediaInterface $a */
    $a = $storage->create([
      'bundle' => $this->testMediaType->id(),
    ]);
    /** @var \Drupal\media\MediaInterface $b */
    $b = $storage->create([
      'bundle' => $this->testMediaType->id(),
    ]);

    // Set a random source value on both items.     $a->set($a->getSource()->getSourceFieldDefinition($a->bundle->entity)->getName()$this->randomString());
    $b->set($b->getSource()->getSourceFieldDefinition($b->bundle->entity)->getName()$this->randomString());

    $a->save();
    $storage->save($b);

    // Assert that the default name was mapped into the name field for both     // media items.     $this->assertFalse($a->get('name')->isEmpty());
    $this->assertFalse($b->get('name')->isEmpty());

    // Assert that arbitrary metadata was mapped correctly.

  public function testTranslatableFieldSaveLoad() {
    /** @var \Drupal\Core\Entity\EntityTypeInterface $entity_type */
    $entity_type = $this->container->get('entity_type.manager')->getDefinition('media');
    $this->assertTrue($entity_type->isTranslatable(), 'Media is translatable.');

    // Check if the translation handler uses the content_translation handler.     $translation_handler_class = $entity_type->getHandlerClass('translation');
    $this->assertEquals(ContentTranslationHandler::class$translation_handler_class, 'Translation handler is set to use the content_translation handler.');

    // Prepare the field translations.     $source_field_definition = $this->testTranslationMediaType->getSource()->getSourceFieldDefinition($this->testTranslationMediaType);
    $source_field_storage = $source_field_definition->getFieldStorageDefinition();
    /** @var \Drupal\Core\Entity\Sql\SqlContentEntityStorage $media_storage */
    $media_storage = $this->container->get('entity_type.manager')->getStorage('media');
    /** @var \Drupal\media\Entity\Media $media */
    $media = $media_storage->create([
      'bundle' => $this->testTranslationMediaType->id(),
      'name' => 'Unnamed',
    ]);

    $field_translations = [];
    $available_langcodes = array_keys($this->container->get('language_manager')->getLanguages());
    
/** * {@inheritdoc} */
  public function createSourceField(MediaTypeInterface $type) {
    return parent::createSourceField($type)->set('settings', ['file_extensions' => 'mp4']);
  }

  /** * {@inheritdoc} */
  public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
    $display->setComponent($this->getSourceFieldDefinition($type)->getName()[
      'type' => 'file_video',
      'label' => 'visually_hidden',
    ]);
  }

}

  protected function getMediaImageSourceFieldName(MediaInterface $media) {
    $field_definition = $media->getSource()
      ->getSourceFieldDefinition($media->bundle->entity);
    $item_class = $field_definition->getItemDefinition()->getClass();
    if (is_a($item_class, ImageItem::class, TRUE)) {
      return $field_definition->getName();
    }
    return NULL;
  }

}
/** * {@inheritdoc} */
  protected function getMediaType(FormStateInterface $form_state) {
    if ($this->mediaType) {
      return $this->mediaType;
    }

    $media_type = parent::getMediaType($form_state);
    // The file upload form only supports media types which use a file field as     // a source field.     $field_definition = $media_type->getSource()->getSourceFieldDefinition($media_type);
    if (!is_a($field_definition->getClass(), FileFieldItemList::class, TRUE)) {
      throw new \InvalidArgumentException('Can only add media types which use a file field as a source field.');
    }
    return $media_type;
  }

  /** * {@inheritdoc} */
  protected function buildInputElement(array $form, FormStateInterface $form_state) {
    // Create a file item to get the upload validators.
foreach (MediaType::loadMultiple() as $media_type) {
      $media_type_machine_name = $media_type->id();
      $this->drupalGet('media/add/' . $media_type_machine_name);
      // Get the form element, and its HTML representation.       $form_selector = '#media-' . Html::cleanCssIdentifier($media_type_machine_name) . '-add-form';
      $form = $assert_session->elementExists('css', $form_selector);
      $form_html = $form->getOuterHtml();

      // The name field should be hidden.       $assert_session->fieldNotExists('Name', $form);
      // The source field should be shown before the vertical tabs.       $source_field_label = $media_type->getSource()->getSourceFieldDefinition($media_type)->getLabel();
      $test_source_field = $assert_session->elementExists('xpath', "//*[contains(text(), '$source_field_label')]", $form)->getOuterHtml();
      $vertical_tabs = $assert_session->elementExists('css', '.js-form-type-vertical-tabs', $form)->getOuterHtml();
      $this->assertGreaterThan(strpos($form_html$test_source_field)strpos($form_html$vertical_tabs));
      // The "Published" checkbox should be the last element.       $date_field = $assert_session->fieldExists('Date', $form)->getOuterHtml();
      $published_checkbox = $assert_session->fieldExists('Published', $form)->getOuterHtml();
      $this->assertGreaterThan(strpos($form_html$date_field)strpos($form_html$published_checkbox));
      if (is_a($media_type->getSource(), Image::class, TRUE)) {
        // Assert the default entity view display is configured with an image         // style.         $this->drupalGet('/admin/structure/media/manage/' . $media_type->id() . '/display');
        

  public function testRender($url$resource_url, array $formatter_settings, array $selectors, bool $self_closing) {
    $account = $this->drupalCreateUser(['view media']);
    $this->drupalLogin($account);

    $media_type = $this->createMediaType('oembed:video');

    $source = $media_type->getSource();
    $source_field = $source->getSourceFieldDefinition($media_type);

    EntityViewDisplay::create([
      'targetEntityType' => 'media',
      'bundle' => $media_type->id(),
      'mode' => 'full',
      'status' => TRUE,
    ])->removeComponent('thumbnail')
      ->setComponent($source_field->getName()[
        'type' => 'oembed',
        'settings' => $formatter_settings,
      ])
      
protected function createMediaItems(array $media_items) {
    $created_items = [];
    $time = time();
    foreach ($media_items as $type => $names) {
      foreach ($names as $name) {
        /** @var \Drupal\media\MediaInterface $media */
        $media = Media::create([
          'name' => $name,
          'bundle' => $type,
        ]);
        $source_field = $media->getSource()
          ->getSourceFieldDefinition($media->bundle->entity)
          ->getName();
        $media->set($source_field$name)->setCreatedTime(++$time)->save();
        $created_items[$name] = $media;
      }
    }
    return $created_items;
  }

  /** * Asserts that text appears on page after a wait. * * @param string $text * The text that should appear on the page. * @param int $timeout * Timeout in milliseconds, defaults to 10000. * * @todo replace with whatever gets added in * https://www.drupal.org/node/3061852 */
/** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    $status = parent::save($form$form_state);
    /** @var \Drupal\media\MediaTypeInterface $media_type */
    $media_type = $this->entity;

    // If the media source is using a source field, ensure it's     // properly created.     $source = $media_type->getSource();
    $source_field = $source->getSourceFieldDefinition($media_type);
    if (!$source_field) {
      $source_field = $source->createSourceField($media_type);
      /** @var \Drupal\field\FieldStorageConfigInterface $storage */
      $storage = $source_field->getFieldStorageDefinition();
      if ($storage->isNew()) {
        $storage->save();
      }
      $source_field->save();

      // Add the new field to the default form and view displays for this       // media type.
/** * {@inheritdoc} */
  public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
    parent::prepareViewDisplay($type$display);

    // Use the `large` image style and do not link the image to anything.     // This will prevent the out-of-the-box configuration from outputting very     // large raw images. If the `large` image style has been deleted, do not     // set an image style.     $field_name = $this->getSourceFieldDefinition($type)->getName();
    $component = $display->getComponent($field_name);
    $component['settings']['image_link'] = '';
    $component['settings']['image_style'] = '';
    if ($this->entityTypeManager->getStorage('image_style')->load('large')) {
      $component['settings']['image_style'] = 'large';
    }
    $display->setComponent($field_name$component);
  }

}

  public function getSourceFieldConstraints() {
    return [
      'oembed_resource' => [],
    ];
  }

  /** * {@inheritdoc} */
  public function prepareViewDisplay(MediaTypeInterface $type, EntityViewDisplayInterface $display) {
    $display->setComponent($this->getSourceFieldDefinition($type)->getName()[
      'type' => 'oembed',
      'label' => 'visually_hidden',
    ]);
  }

  /** * {@inheritdoc} */
  public function prepareFormDisplay(MediaTypeInterface $type, EntityFormDisplayInterface $display) {
    parent::prepareFormDisplay($type$display);
    $source_field = $this->getSourceFieldDefinition($type)->getName();

    
/** * Get image field from source config. * * @param \Drupal\media\MediaInterface $media * A media entity. * * @return string|null * String of image field name. */
  protected function getMediaImageSourceField(MediaInterface $media) {
    $field_definition = $media->getSource()
      ->getSourceFieldDefinition($media->bundle->entity);
    $item_class = $field_definition->getItemDefinition()->getClass();
    if ($item_class == ImageItem::class || is_subclass_of($item_class, ImageItem::class)) {
      return $field_definition->getName();
    }
    return NULL;
  }

  /** * {@inheritdoc} */
  public static function trustedCallbacks() {
    

  protected $defaultTheme = 'stark';

  /** * Tests that the requirements check can handle a missing source field. */
  public function testMissingSourceFieldDefinition() {
    $media_type = $this->createMediaType('test');
    /** @var \Drupal\field\FieldConfigInterface $field_definition */
    $field_definition = $media_type->getSource()
      ->getSourceFieldDefinition($media_type);
    /** @var \Drupal\field\FieldStorageConfigInterface $field_storage_definition */
    $field_storage_definition = $field_definition->getFieldStorageDefinition();
    $field_definition->delete();
    $field_storage_definition->delete();
    $valid_media_type = $this->createMediaType('test');

    $this->drupalLogin($this->rootUser);
    $this->drupalGet('/admin/reports/status');
    $this->assertSession()->statusCodeEquals(200);
    $this->assertSession()->pageTextContains("The source field definition for the {$media_type->label()} media type is missing.");
    $this->assertSession()->pageTextNotContains("The source field definition for the {$valid_media_type->label()} media type is missing.");
  }
Home | Imprint | This part of the site doesn't use cookies.