I've created a field with drupal console. That made the following standard folder structure.


These all have their respected php classes.

Now this field is in a content type that always is used in a Book. I want to this Books name into that field. I know how to retrieve this name trough code but i don't know how to get this value into this field in all new instances of this content type.

I thought i just needed to use a default value but that doesn't seem to work because even though i added 'default' to the schema with that value it doesn't show up?

1 Answer 1


Normally a default value is configured in the field configuration. Either static in default_value or dynamic in default_value_callback pointing to a callback function which returns the default value.

For your original question, how to do this in one of the field plugins, see No way for a field to dynamically set default value and especially #6:

I resorted to creating widgets (extending the base widgets), whose only concern is to set the default value dynamically according to contextual values, e.g. I have a widget that presets a default value to an entity name referenced by the logged in user, something like this:

 * Define the {@link AcmeWidget} class.
 * @FieldWidget(
 *   id = "acme_widget",
 *   label = @Translation("Acme Textfield"),
 *   field_types = {
 *     "string"
 *   }
 * )
 * @package Drupal\acme\Plugin\Field\FieldWidget
class AcmeWidget extends StringTextfieldWidget {

   * {@inheritdoc}
  public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {

    // Call our parent but set the value using our default value function.
    $element = parent::formElement($items, $delta, $element, $form, $form_state);

    // Get the current user organization's name.
    $user = User::load(\Drupal::currentUser()->id());
    $organization = $user->get('field_organization')->entity->title->value;

    // Set the default value if a value hasn't been set.
    $element['value']['#default_value'] = $organization;

    return $element;


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.