getFieldStorageDefinition example

// Check that the image item can be set to the referenced file directly.     $entity->image_test = $this->image;
    $this->assertEquals($this->image->id()$entity->image_test->target_id);

    // Delete the image and try to save the entity again.     $this->image->delete();
    $entity = EntityTest::create(['name' => $this->randomMachineName()]);
    $entity->save();

    // Test image item properties.     $expected = ['target_id', 'entity', 'alt', 'title', 'width', 'height'];
    $properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
    $this->assertEquals($expectedarray_keys($properties));

  }

  /** * Tests generateSampleItems() method under different resolutions. */
  public function testImageItemSampleValueGeneration() {

    // Default behaviour. No resolution configuration.     $entity = EntityTest::create();
    


    return $plugins;
  }

  /** * {@inheritdoc} */
  public function getSelectionHandler(FieldDefinitionInterface $field_definition, EntityInterface $entity = NULL) {
    $options = $field_definition->getSetting('handler_settings') ?: [];
    $options += [
      'target_type' => $field_definition->getFieldStorageDefinition()->getSetting('target_type'),
      'handler' => $field_definition->getSetting('handler'),
      'entity' => $entity,
    ];
    return $this->getInstance($options);
  }

  /** * {@inheritdoc} */
  public function getFallbackPluginId($plugin_id, array $configuration = []) {
    return 'broken';
  }
$expected_entity_type$expected_bundle$expected_name] = explode('.', $id);

    /** @var \Drupal\field\FieldConfigInterface $field */
    $field = FieldConfig::load($id);
    $this->assertInstanceOf(FieldConfigInterface::class$field);
    $this->assertEquals($expected_label$field->label());
    $this->assertEquals($expected_field_type$field->getType());
    $this->assertEquals($expected_entity_type$field->getTargetEntityTypeId());
    $this->assertEquals($expected_bundle$field->getTargetBundle());
    $this->assertEquals($expected_name$field->getName());
    $this->assertEquals($is_required$field->isRequired());
    $this->assertEquals($expected_entity_type . '.' . $expected_name$field->getFieldStorageDefinition()->id());
    $this->assertEquals($expected_translatable$field->isTranslatable());
  }

  /** * Asserts the settings of a link field config entity. * * @param string $id * The entity ID in the form ENTITY_TYPE.BUNDLE.FIELD_NAME. * @param int $title_setting * The expected title setting. * * @internal */
$entity = $storage->create($values);
    }

    $items = $entity->get($field_name);
    $field_definition = $items->getFieldDefinition();

    // Check that the field is an entity reference, or subclass of it, since we     // need to check the target_type setting.     if (!$items instanceof EntityReferenceFieldItemList) {
      throw new \LogicException('Expected the media library to be opened by an entity reference field.');
    }
    if ($field_definition->getFieldStorageDefinition()->getSetting('target_type') !== 'media') {
      throw new \LogicException('Expected the media library to be opened by an entity reference field that target media items.');
    }

    $field_access = $access_handler->fieldAccess('edit', $field_definition$account$items, TRUE);
    $access = $entity_access->andIf($field_access);
    if ($access instanceof RefinableCacheableDependencyInterface) {
      $access->addCacheableDependency($state);
    }
    return $access;
  }

  
$form[$name]['#access'] = $items->access('edit');

        // Assign the correct weight. This duplicates the reordering done in         // processForm(), but is needed for other forms calling this method         // directly.         $form[$name]['#weight'] = $options['weight'];

        // Associate the cache tags for the field definition & field storage         // definition.         $field_definition = $this->getFieldDefinition($name);
        $this->renderer->addCacheableDependency($form[$name]$field_definition);
        $this->renderer->addCacheableDependency($form[$name]$field_definition->getFieldStorageDefinition());
      }
    }

    // Associate the cache tags for the form display.     $this->renderer->addCacheableDependency($form$this);

    // Add a process callback so we can assign weights and hide extra fields.     $form['#process'][] = [$this, 'processForm'];
  }

  /** * Process callback: assigns weights and hides extra fields. * * @see \Drupal\Core\Entity\Entity\EntityFormDisplay::buildForm() */
return $this->entityKeys[$key];
    }
    if (isset($this->translatableEntityKeys[$key][$this->activeLangcode])) {
      return $this->translatableEntityKeys[$key][$this->activeLangcode];
    }

    // Otherwise fetch the value by creating a field object.     $value = NULL;
    if ($this->getEntityType()->hasKey($key)) {
      $field_name = $this->getEntityType()->getKey($key);
      $definition = $this->getFieldDefinition($field_name);
      $property = $definition->getFieldStorageDefinition()->getMainPropertyName();
      $value = $this->get($field_name)->$property;

      // Put it in the right array, depending on whether it is translatable.       if ($definition->isTranslatable()) {
        $this->translatableEntityKeys[$key][$this->activeLangcode] = $value;
      }
      else {
        $this->entityKeys[$key] = $value;
      }
    }
    else {
      
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());
    $media->set('langcode', reset($available_langcodes));
    
$parents = $form['#parents'];

    // Load the items for form rebuilds from the field state as they might not     // be in $form_state->getValues() because of validation limitations. Also,     // they are only passed in as $items when editing existing entities.     $field_state = static::getWidgetState($parents$field_name$form_state);
    if (isset($field_state['items'])) {
      $items->setValue($field_state['items']);
    }

    // Determine the number of widgets to display.     $cardinality = $this->fieldDefinition->getFieldStorageDefinition()->getCardinality();
    switch ($cardinality) {
      case FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED:
        $max = count($items);
        $is_multiple = TRUE;
        break;

      default:
        $max = $cardinality - 1;
        $is_multiple = ($cardinality > 1);
        break;
    }

    


  /** * {@inheritdoc} */
  public function setEntity(ConfigEntityInterface $entity) {
    if (parent::setEntity($entity)) {

      // Field storage config can also contain translatable values. Add the name       // of the config as well to the list of configs for this entity.       /** @var \Drupal\field\FieldStorageConfigInterface $field_storage */
      $field_storage = $this->entity->getFieldStorageDefinition();
      /** @var \Drupal\Core\Config\Entity\ConfigEntityTypeInterface $entity_type_info */
      $entity_type_info = $this->entityTypeManager->getDefinition($field_storage->getEntityTypeId());
      $this->addConfigName($entity_type_info->getConfigPrefix() . '.' . $field_storage->id());
      return TRUE;
    }
    return FALSE;
  }

}
->willReturn($this->prophesize(FieldItemListInterface::class)->reveal());
    $this->fieldItem->getFieldDefinition()->willReturn($this->fieldDefinition->reveal());
    if (!empty($data['target_uuid'])) {
      $this->fieldDefinition
        ->getSetting('target_type')
        ->willReturn('test_type')
        ->shouldBeCalled();
    }

    // Avoid a static method call by returning dummy serialized property data.     $this->fieldDefinition
      ->getFieldStorageDefinition()
      ->willReturn()
      ->shouldBeCalled();
    $this->fieldDefinition
      ->getName()
      ->willReturn('field_reference')
      ->shouldBeCalled();
    $entity = $this->prophesize(EntityInterface::class);
    $entity_type = $this->prophesize(EntityTypeInterface::class);
    $entity->getEntityType()
      ->willReturn($entity_type->reveal())
      ->shouldBeCalled();
    
$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.       if ($source_field->isDisplayConfigurable('form')) {
        $display = $this->entityDisplayRepository->getFormDisplay('media', $media_type->id());
        $source->prepareFormDisplay($media_type$display);
        $display->save();
      }
$this->setValue($values);
  }

  /** * {@inheritdoc} */
  public function getConstraints() {
    $constraints = parent::getConstraints();
    // Check that the number of values doesn't exceed the field cardinality. For     // form submitted values, this can only happen with 'multiple value'     // widgets.     $cardinality = $this->getFieldDefinition()->getFieldStorageDefinition()->getCardinality();
    if ($cardinality != FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED) {
      $constraints[] = $this->getTypedDataManager()
        ->getValidationConstraintManager()
        ->create('Count', [
          'max' => $cardinality,
          'maxMessage' => t('%name: this field cannot hold more than @count values.', ['%name' => $this->getFieldDefinition()->getLabel(), '@count' => $cardinality]),
        ]);
    }

    return $constraints;
  }

  

  protected function assertEntity(string $bundle, string $field_name, int $default_value, int $default_mode, int $per_page, int $anonymous, bool $form_location, int $preview): void {
    $entity = FieldConfig::load("node.$bundle.$field_name");
    $this->assertInstanceOf(FieldConfig::class$entity);
    $this->assertSame('node', $entity->getTargetEntityTypeId());
    $this->assertSame('Comments', $entity->label());
    $this->assertTrue($entity->isRequired());
    $this->assertSame($bundle$entity->getTargetBundle());
    $this->assertSame($field_name$entity->getFieldStorageDefinition()->getName());
    $this->assertSame($default_value$entity->get('default_value')[0]['status']);
    $this->assertSame($default_mode$entity->getSetting('default_mode'));
    $this->assertSame($per_page$entity->getSetting('per_page'));
    $this->assertSame($anonymous$entity->getSetting('anonymous'));
    $this->assertSame($form_location$entity->getSetting('form_location'));
    $this->assertSame($preview$entity->getSetting('preview'));
  }

  /** * Tests the migrated field instance values. */
  
$source = $media_type->getSource();
    $source_field = $source->createSourceField($media_type);
    $source_configuration = $source->getConfiguration();
    $source_configuration['source_field'] = $source_field->getName();
    $source->setConfiguration($source_configuration);

    $this->assertSame(SAVED_NEW, $media_type->save());

    // The media type form creates a source field if it does not exist yet. The     // same must be done in a kernel test, since it does not use that form.     // @see \Drupal\media\MediaTypeForm::save()     $source_field->getFieldStorageDefinition()->save();
    // The source field storage has been created, now the field can be saved.     $source_field->save();

    // Add the source field to the form display for the media type.     $form_display = \Drupal::service('entity_display.repository')->getFormDisplay('media', $media_type->id(), 'default');
    $source->prepareFormDisplay($media_type$form_display);
    $form_display->save();

    return $media_type;
  }

}
    // @see \Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface::DATE_STORAGE_FORMAT     'date-only' => 'Y-m-d',
  ];

  /** * {@inheritdoc} */
  public function normalize($datetime$format = NULL, array $context = []): array|string|int|float|bool|\ArrayObject|NULL {
    assert($datetime instanceof DateTimeIso8601);
    $field_item = $datetime->getParent();
    // @todo Remove this in https://www.drupal.org/project/drupal/issues/2958416.     if ($field_item instanceof DateTimeItem && $field_item->getFieldDefinition()->getFieldStorageDefinition()->getSetting('datetime_type') === DateTimeItem::DATETIME_TYPE_DATE) {
      $drupal_date_time = $datetime->getDateTime();
      if ($drupal_date_time === NULL) {
        return $drupal_date_time;
      }
      return $drupal_date_time->format($this->allowedFormats['date-only']);
    }
    return parent::normalize($datetime$format$context);
  }

  /** * {@inheritdoc} */
Home | Imprint | This part of the site doesn't use cookies.