setDefaultValueCallback example

$this->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
    $this->assertSession()->fieldValueEquals('default_value_input[field_test][0][value]', $default_value);

    // Set a different field value to the field directly, instead of an array.     $default_value = $this->randomString();
    $field_config->setDefaultValue($default_value)->save();
    $this->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
    $this->assertSession()->fieldValueEquals('default_value_input[field_test][0][value]', $default_value);

    // Set a default value callback instead, and the default field form should     // not be visible.     $field_config->setDefaultValueCallback('\Drupal\field_test\FieldDefaultValueCallbackProvider::calculateDefaultValue')->save();
    $this->drupalGet('/admin/structure/types/manage/article/fields/node.article.field_test');
    $this->assertSession()->fieldNotExists('default_value_input[field_test][0][value]');
  }

}

    ];
  }

  /** * Tests the default value callback. */
  public function testDefaultValueCallback() {
    $base_field = BaseFieldDefinition::create('entity_reference')
      ->setName('Test Field')
      ->setTargetEntityTypeId('entity_test')
      ->setDefaultValueCallback(static::class D '::defaultValueCallbackPrimitive');
    $base_field_override = BaseFieldOverride::createFromBaseFieldDefinition($base_field, 'test_bundle');
    $entity = EntityTest::create([]);

    $this->assertEquals([['target_id' => 99]]$base_field->getDefaultValue($entity));
    $this->assertEquals([['target_id' => 99]]$base_field_override->getDefaultValue($entity));
  }

  /** * A default value callback which returns a primitive value. * * @return int * A primitive default value. */
throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not implement \Drupal\user\EntityOwnerInterface.');
    }
    if (!$entity_type->hasKey('owner')) {
      throw new UnsupportedEntityTypeDefinitionException('The entity type ' . $entity_type->id() . ' does not have an "owner" entity key.');
    }

    return [
      $entity_type->getKey('owner') => BaseFieldDefinition::create('entity_reference')
        ->setLabel(new TranslatableMarkup('User ID'))
        ->setSetting('target_type', 'user')
        ->setTranslatable($entity_type->isTranslatable())
        ->setDefaultValueCallback(static::class D '::getDefaultEntityOwner'),
    ];
  }

  /** * {@inheritdoc} */
  public function getOwnerId() {
    return $this->getEntityKey('owner');
  }

  /** * {@inheritdoc} */
->setInitialValue(FALSE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    if (!$this->hasAuthor()) {
      $definitions['content_translation_uid'] = BaseFieldDefinition::create('entity_reference')
        ->setLabel(t('Translation author'))
        ->setDescription(t('The author of this translation.'))
        ->setSetting('target_type', 'user')
        ->setSetting('handler', 'default')
        ->setRevisionable(TRUE)
        ->setDefaultValueCallback(static::class D '::getDefaultOwnerId')
        ->setTranslatable(TRUE);
    }

    if (!$this->hasPublishedStatus()) {
      $definitions['content_translation_status'] = BaseFieldDefinition::create('boolean')
        ->setLabel(t('Translation status'))
        ->setDescription(t('A boolean indicating whether the translation is visible to non-translators.'))
        ->setDefaultValue(TRUE)
        ->setInitialValue(TRUE)
        ->setRevisionable(TRUE)
        ->setTranslatable(TRUE);
    }
$fields['cid']->setLabel(t('Comment ID'))
      ->setDescription(t('The comment ID.'));

    $fields['uuid']->setDescription(t('The comment UUID.'));

    $fields['comment_type']->setLabel(t('Comment Type'))
      ->setDescription(t('The comment type.'));

    $fields['langcode']->setDescription(t('The comment language code.'));

    // Set the default value callback for the status field.     $fields['status']->setDefaultValueCallback('Drupal\comment\Entity\Comment::getDefaultStatus');

    $fields['pid'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Parent ID'))
      ->setDescription(t('The parent comment ID if this is a reply to a comment.'))
      ->setSetting('target_type', 'comment');

    $fields['entity_id'] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Entity ID'))
      ->setDescription(t('The ID of the entity of which this comment is a reply.'))
      ->setRequired(TRUE);

    
/** * Tests default value callbacks. * * @covers ::setDefaultValueCallback * @dataProvider factoryTypeProvider */
  public function testDefaultValueCallback($factory_name) {
    $definition = $this->initializeFieldUsingFactory($factory_name);
    $callback = static::class D '::mockDefaultValueCallback';
    // setDefaultValueCallback returns $this.     $this->assertSame($definition$definition->setDefaultValueCallback($callback));
    $this->assertSame($callback$definition->getDefaultValueCallback());
  }

  /** * Tests invalid default value callbacks. * * @covers ::setDefaultValueCallback * @dataProvider factoryTypeProvider */
  public function testInvalidDefaultValueCallback($factory_name) {
    $definition = $this->initializeFieldUsingFactory($factory_name);
    
// String field with default callback.     $field_storage = FieldStorageConfig::create([
      'field_name' => 'field_string_with_callback',
      'entity_type' => 'node',
      'type' => 'string',
    ]);
    $field_storage->save();
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      'bundle' => 'test_node_type',
    ]);
    $field->setDefaultValueCallback('Drupal\Tests\layout_builder\Functional\LayoutBuilderDefaultValuesTest::defaultValueCallback');
    $field->save();

    // String field with late default. We will set default later.     $field_storage = FieldStorageConfig::create([
      'field_name' => 'field_string_late_default',
      'entity_type' => 'node',
      'type' => 'string',
    ]);
    $field_storage->save();
    $field = FieldConfig::create([
      'field_storage' => $field_storage,
      
class EntityTestMulDefaultValue extends EntityTestMul {

  /** * {@inheritdoc} */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['description'] = BaseFieldDefinition::create('shape')
      ->setLabel(t('Some custom description'))
      ->setTranslatable(TRUE)
      ->setDefaultValueCallback('entity_test_field_default_value');

    return $fields;
  }

}

class EntityTestDefaultValue extends EntityTest {

  /** * {@inheritdoc} */
  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);

    $fields['description'] = BaseFieldDefinition::create('shape')
      ->setLabel(t('Some custom description'))
      ->setDefaultValueCallback('entity_test_field_default_value');

    return $fields;
  }

}
'display_label' => TRUE,
        ],
        'weight' => 100,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['created'] = BaseFieldDefinition::create('created')
      ->setLabel(t('Authored on'))
      ->setDescription(t('The time the media item was created.'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE)
      ->setDefaultValueCallback(static::class D '::getRequestTime')
      ->setDisplayOptions('form', [
        'type' => 'datetime_timestamp',
        'weight' => 10,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayOptions('view', [
        'label' => 'hidden',
        'type' => 'timestamp',
        'weight' => 0,
      ])
      ->setDisplayConfigurable('view', TRUE);

    


  /** * Tests default value callbacks. * * @covers ::setDefaultValueCallback */
  public function testDefaultValueCallback() {
    $definition = BaseFieldDefinition::create($this->fieldType);
    $callback = static::class D '::mockDefaultValueCallback';
    // setDefaultValueCallback returns $this.     $this->assertSame($definition$definition->setDefaultValueCallback($callback));
  }

  /** * Tests invalid default value callbacks. * * @covers ::setDefaultValueCallback */
  public function testInvalidDefaultValueCallback() {
    $definition = BaseFieldDefinition::create($this->fieldType);
    // setDefaultValueCallback returns $this.     $this->expectException(\InvalidArgumentException::class);
    
Home | Imprint | This part of the site doesn't use cookies.