getDefaultValueCallback example

const DEFAULT_VALUE_NOW = 'now';

  /** * 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'),
            
// 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) {
      if ($settings = $form->getComponent($field_name)) {
        
'maxMessage' => t('%name: this field cannot hold more than @count values.', ['%name' => $this->getFieldDefinition()->getLabel(), '@count' => $cardinality]),
        ]);
    }

    return $constraints;
  }

  /** * {@inheritdoc} */
  public function defaultValuesForm(array &$form, FormStateInterface $form_state) {
    if (empty($this->getFieldDefinition()->getDefaultValueCallback())) {
      if ($widget = $this->defaultValueWidget($form_state)) {
        // Place the input in a separate place in the submitted values tree.         $element = ['#parents' => ['default_value_input']];
        $element += $widget->form($this$element$form_state);

        return $element;
      }
      else {
        return ['#markup' => $this->t('No widget available for: %type.', ['%type' => $this->getFieldDefinition()->getType()])];
      }
    }
  }
use Drupal\datetime\Plugin\Field\FieldType\DateTimeItemInterface;

/** * 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.'),
        

  public function setDefaultValue($value) {
    $this->definition['default_value'] = $this->normalizeValue($value$this->getFieldStorageDefinition()->getMainPropertyName());
    return $this;
  }

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

  

  public function setRequired($required) {
    $this->required = $required;
    return $this;
  }

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

  

  public function getDefaultValueCallback() {
    return $this->definition['default_value_callback'] ?? NULL;
  }

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

  
/** * 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);
    // setDefaultValueCallback returns $this.
Home | Imprint | This part of the site doesn't use cookies.