getDefaultValueLiteral example

// Import a stub row.     $row = new Row([][], TRUE);
    $row->setDestinationProperty('type', 'test');
    $ids = $this->destination->import($row);
    $this->assertCount(1, $ids);

    // Make sure the entity was saved.     $entity = EntityTestMul::load(reset($ids));
    $this->assertInstanceOf(EntityTestMul::class$entity);
    // Make sure the default value was applied to the required fields.     $single_field_name = 'required_default_field';
    $single_default_value = $entity->getFieldDefinition($single_field_name)->getDefaultValueLiteral();
    $this->assertSame($single_default_value$entity->get($single_field_name)->getValue());

    $multi_field_name = 'required_multi_default_field';
    $multi_default_value = $entity->getFieldDefinition($multi_field_name)->getDefaultValueLiteral();
    $count = 3;
    $this->assertCount($count$multi_default_value);
    for ($i = 0; $i < $count; ++$i) {
      $this->assertSame($multi_default_value[$i]$entity->get($multi_field_name)->get($i)->getValue());
    }
  }

  

  }

  /** * @covers ::getDefaultValue * @covers ::setDefaultValue * @dataProvider factoryTypeProvider */
  public function testFieldDefaultValue($factory_name) {
    $definition = $this->initializeFieldUsingFactory($factory_name);

    $this->assertEquals([]$definition->getDefaultValueLiteral());

    $default_value = [
      'value' => $this->randomMachineName(),
    ];
    $expected_default_value = [$default_value];
    $definition->setDefaultValue($default_value);
    $entity = $this->getMockBuilder('Drupal\Core\Entity\ContentEntityBase')
      ->disableOriginalConstructor()
      ->getMock();
    // Set the field item list class to be used to avoid requiring the typed     // data manager to retrieve it.
    $edit = [$element_name => '-1', 'set_default_value' => '1'];
    $this->drupalGet($admin_path);
    $this->submitForm($edit, 'Save settings');
    $this->assertSession()->pageTextContains("$field_name does not accept the value -1");

    // Check that the default value is saved.     $edit = [$element_name => '1', 'set_default_value' => '1'];
    $this->drupalGet($admin_path);
    $this->submitForm($edit, 'Save settings');
    $this->assertSession()->pageTextContains("Saved $field_name configuration");
    $field = FieldConfig::loadByName('node', $this->contentType, $field_name);
    $this->assertEquals([['value' => 1]]$field->getDefaultValueLiteral(), 'The default value was correctly saved.');

    // Check that the default value shows up in the form.     $this->drupalGet($admin_path);
    $this->assertSession()->fieldValueEquals($element_id, '1');

    // Check that the default value is left empty when "Set default value"     // checkbox is not checked.     $edit = [$element_name => '1', 'set_default_value' => '0'];
    $this->drupalGet($admin_path);
    $this->submitForm($edit, 'Save settings');
    $this->assertSession()->pageTextContains("Saved $field_name configuration");
    
/** * Defines the default value as relative. */
  const DEFAULT_VALUE_CUSTOM = 'relative';

  /** * {@inheritdoc} */
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
    if (empty($this->getFieldDefinition()->getDefaultValueCallback())) {
      $default_value = $this->getFieldDefinition()->getDefaultValueLiteral();

      $element = [
        '#parents' => ['default_value_input'],
        'default_date_type' => [
          '#type' => 'select',
          '#title' => $this->t('Default date'),
          '#description' => $this->t('Set a default value for this date.'),
          '#default_value' => $default_value[0]['default_date_type'] ?? '',
          '#options' => [
            static::DEFAULT_VALUE_NOW => $this->t('Current date'),
            static::DEFAULT_VALUE_CUSTOM => $this->t('Relative date'),
          ],


  /** * {@inheritdoc} */
  public function getDefaultValue(FieldableEntityInterface $entity) {
    // Allow custom default values function.     if ($callback = $this->getDefaultValueCallback()) {
      $value = call_user_func($callback$entity$this);
    }
    else {
      $value = $this->getDefaultValueLiteral();
    }
    $value = $this->normalizeValue($value$this->getFieldStorageDefinition()->getMainPropertyName());
    // Allow the field type to process default values.     $field_item_list_class = $this->getClass();
    return $field_item_list_class::processDefaultValue($value$entity$this);
  }

  /** * Sets whether the field is translatable. * * @param bool $translatable * Whether the field is translatable. * * @return $this */
// Check that the 'comment_body' field exists and has an instance on the     // new comment bundle.     $field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
    $this->assertInstanceOf(FieldStorageConfig::class$field_storage);
    $field = FieldConfig::loadByName('comment', 'comment', 'comment_body');
    $this->assertTrue(isset($field)new FormattableMarkup('The comment_body field is present for comments on type @type', ['@type' => $type_name]));

    // Test adding a field that defaults to CommentItemInterface::CLOSED.     $this->addDefaultCommentField('node', 'test_node_type', 'who_likes_ponies', CommentItemInterface::CLOSED, 'who_likes_ponies');
    $field = FieldConfig::load('node.test_node_type.who_likes_ponies');
    $this->assertEquals(CommentItemInterface::CLOSED, $field->getDefaultValueLiteral()[0]['status']);
  }

  /** * Tests that you can remove a comment field. */
  public function testCommentFieldDelete() {
    $this->drupalCreateContentType(['type' => 'test_node_type']);
    $this->addDefaultCommentField('node', 'test_node_type');
    // We want to test the handling of removing the primary comment field, so we     // ensure there is at least one other comment field attached to a node type     // so that comment_entity_load() runs for nodes.
/** * {@inheritdoc} */
  public function getDefaultValue(FieldableEntityInterface $entity) {
    // Allow custom default values function.     if ($callback = $this->getDefaultValueCallback()) {
      $value = call_user_func($callback$entity$this);
      $value = $this->normalizeValue($value$this->getFieldStorageDefinition()->getMainPropertyName());
    }
    else {
      $value = $this->getDefaultValueLiteral();
    }
    // Allow the field type to process default values.     $field_item_list_class = $this->getClass();
    return $field_item_list_class::processDefaultValue($value$entity$this);
  }

  /** * {@inheritdoc} */
  public function getDefaultValueLiteral() {
    return $this->default_value;
  }
$this->assertInstanceOf(FieldConfig::class$field);
    $this->assertSame('Date Field', $field->label());
    $this->assertSame('An example date field.', $field->getDescription());
    $expected = ['datetime_type' => 'datetime'];
    $this->assertSame($expected$field->getSettings());
    $expected = [
      [
        'default_date_type' => 'relative',
        'default_date' => 'blank',
      ],
    ];
    $this->assertSame($expected$field->getDefaultValueLiteral());
    $this->assertTrue($field->isTranslatable());

    // Test datetime field.     $field = FieldConfig::load('node.story.field_test_datetime');
    $this->assertInstanceOf(FieldConfig::class$field);
    $this->assertSame('Datetime Field', $field->label());
    $this->assertSame('An example datetime field.', $field->getDescription());
    $expected = ['datetime_type' => 'datetime'];
    $this->assertSame($expected$field->getSettings());
    $expected = [];
    $this->assertSame($expected$field->getDefaultValueLiteral());
    
$translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
      $translation->{$this->fieldName}->setValue($values[$this->fieldName][$langcode]);
    }

    $field_langcodes = array_keys($entity->getTranslationLanguages());
    sort($field_langcodes);
    $this->assertEquals($translation_langcodes$field_langcodes, 'Missing translations did not get a default value.');

    // @todo Test every translation once the Entity Translation API allows for     // multilingual defaults.     $langcode = $entity->language()->getId();
    $this->assertEquals($field->getDefaultValueLiteral()$entity->getTranslation($langcode)->{$field_name_default}->getValue()new FormattableMarkup('Default value correctly populated for language %language.', ['%language' => $langcode]));

    $storage = \Drupal::entityTypeManager()->getStorage($entity_type_id);
    // Check that explicit empty values are not overridden with default values.     foreach ([NULL, []] as $empty_items) {
      $values = ['type' => $field->getTargetBundle(), 'langcode' => $translation_langcodes[0]];
      $entity = $storage->create($values);
      foreach ($translation_langcodes as $langcode) {
        $values[$this->fieldName][$langcode] = $this->_generateTestFieldValues($this->fieldStorage->getCardinality());
        $translation = $entity->hasTranslation($langcode) ? $entity->getTranslation($langcode) : $entity->addTranslation($langcode);
        $translation->{$this->fieldName}->setValue($values[$this->fieldName][$langcode]);
        $translation->{$field_name_default}->setValue($empty_items);
        
// Sort bundles to ensure deterministic behavior.     sort($bundles);
    $existing_bundle = reset($bundles);

    // Copy field configuration.     $existing_field = $this->entityFieldManager->getFieldDefinitions($this->entityTypeId, $existing_bundle)[$field_name];
    $default_options['field_config'] = [
      'description' => $existing_field->getDescription(),
      'settings' => $existing_field->getSettings(),
      'required' => $existing_field->isRequired(),
      'default_value' => $existing_field->getDefaultValueLiteral(),
      'default_value_callback' => $existing_field->getDefaultValueCallback(),
    ];

    // Copy form and view mode configuration.     $properties = [
      'targetEntityType' => $this->entityTypeId,
      'bundle' => $existing_bundle,
    ];
    /** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $existing_forms */
    $existing_forms = $this->entityTypeManager->getStorage('entity_form_display')->loadByProperties($properties);
    foreach ($existing_forms as $form) {
      

      $row->setDestinationProperty($bundle_keyreset($this->bundles));
    }

    $bundle = $row->getDestinationProperty($bundle_key) ?? $this->storage->getEntityTypeId();
    // Populate any required fields not already populated.     $fields = $this->entityFieldManager
      ->getFieldDefinitions($this->storage->getEntityTypeId()$bundle);
    foreach ($fields as $field_name => $field_definition) {
      if ($field_definition->isRequired() && is_null($row->getDestinationProperty($field_name))) {
        // Use the configured default value for this specific field, if any.         if ($default_value = $field_definition->getDefaultValueLiteral()) {
          $values = $default_value;
        }
        else {
          /** @var \Drupal\Core\Field\FieldItemInterface $field_type_class */
          $field_type_class = $this->fieldTypeManager
            ->getPluginClass($field_definition->getType());
          $values = $field_type_class::generateSampleValue($field_definition);
          if (is_null($values)) {
            // Handle failure to generate a sample value.             throw new MigrateException('Stubbing failed, unable to generate value for field ' . $field_name);
          }
        }


  /** * {@inheritdoc} */
  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();
          }
        }
      }
    }


  /** * {@inheritdoc} */
  public function getDefaultValue(FieldableEntityInterface $entity) {
    // Allow custom default values function.     if ($callback = $this->getDefaultValueCallback()) {
      $value = call_user_func($callback$entity$this);
    }
    else {
      $value = $this->getDefaultValueLiteral();
    }
    $value = $this->normalizeValue($value$this->getMainPropertyName());
    // Allow the field type to process default values.     $field_item_list_class = $this->getClass();
    return $field_item_list_class::processDefaultValue($value$entity$this);
  }

  /** * {@inheritdoc} */
  public function setDefaultValue($value) {
    
/** * Represents a configurable entity daterange field. */
class DateRangeFieldItemList extends DateTimeFieldItemList {

  /** * {@inheritdoc} */
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
    if (empty($this->getFieldDefinition()->getDefaultValueCallback())) {
      $default_value = $this->getFieldDefinition()->getDefaultValueLiteral();

      $element = parent::defaultValuesForm($form$form_state);

      $element['default_date_type']['#title'] = $this->t('Default start date');
      $element['default_date_type']['#description'] = $this->t('Set a default value for the start date.');

      $element['default_end_date_type'] = [
        '#type' => 'select',
        '#title' => $this->t('Default end date'),
        '#description' => $this->t('Set a default value for the end date.'),
        '#default_value' => $default_value[0]['default_end_date_type'] ?? '',
        
Home | Imprint | This part of the site doesn't use cookies.