setDefaultValue example

foreach ($default_value as $key => $value) {
        if (is_array($value) && isset($value['target_uuid'])) {
          $entity = $entity_repository->loadEntityByUuid($target_entity_type->id()$value['target_uuid']);
          // @see \Drupal\Core\Field\EntityReferenceFieldItemList::processDefaultValue()           if ($entity && isset($dependencies[$entity->getConfigDependencyKey()][$entity->getConfigDependencyName()])) {
            unset($default_value[$key]);
            $changed = TRUE;
          }
        }
      }
      if ($changed) {
        $field_definition->setDefaultValue($default_value);
      }
    }

    // Update the 'target_bundles' handler setting if a bundle config dependency     // has been removed.     $bundles_changed = FALSE;
    $handler_settings = $field_definition->getSetting('handler_settings');
    if (!empty($handler_settings['target_bundles'])) {
      if ($bundle_entity_type_id = $target_entity_type->getBundleEntityType()) {
        if ($storage = $entity_type_manager->getStorage($bundle_entity_type_id)) {
          foreach ($storage->loadMultiple($handler_settings['target_bundles']) as $bundle) {
            
$fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the node was last edited.'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    $fields['promote'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Promoted to front page'))
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE)
      ->setDefaultValue(TRUE)
      ->setDisplayOptions('form', [
        'type' => 'boolean_checkbox',
        'settings' => [
          'display_label' => TRUE,
        ],
        'weight' => 15,
      ])
      ->setDisplayConfigurable('form', TRUE);

    $fields['sticky'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Sticky at top of lists'))
      
$node = $this->instantiateNode();

        if (isset($this->normalization)) {
            $node->setNormalizationClosures($this->normalization->before);
        }

        if (isset($this->merge)) {
            $node->setAllowOverwrite($this->merge->allowOverwrite);
        }

        if (true === $this->default) {
            $node->setDefaultValue($this->defaultValue);
        }

        $node->setAllowEmptyValue($this->allowEmptyValue);
        $node->addEquivalentValue(null, $this->nullEquivalent);
        $node->addEquivalentValue(true, $this->trueEquivalent);
        $node->addEquivalentValue(false, $this->falseEquivalent);
        $node->setRequired($this->required);

        if ($this->deprecation) {
            $node->setDeprecated($this->deprecation['package']$this->deprecation['version']$this->deprecation['message']);
        }

        
$fields['changed'] = BaseFieldDefinition::create('changed')
      ->setLabel(t('Changed'))
      ->setDescription(t('The time that the content block was last edited.'))
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE);

    $fields['reusable'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Reusable'))
      ->setDescription(t('A boolean indicating whether this block is reusable.'))
      ->setTranslatable(FALSE)
      ->setRevisionable(FALSE)
      ->setDefaultValue(TRUE);

    return $fields;
  }

  /** * {@inheritdoc} */
  public function setInfo($info) {
    $this->set('info', $info);
    return $this;
  }

  

  public function submitForm(array &$form, FormStateInterface $form_state) {
    parent::submitForm($form$form_state);

    // Handle the default value.     $default_value = [];
    if (isset($form['default_value']) && (!isset($form['set_default_value']) || $form_state->getValue('set_default_value'))) {
      $items = $this->getTypedData($form['#entity']);
      $default_value = $items->defaultValuesFormSubmit($form['default_value']$form$form_state);
    }
    $this->entity->setDefaultValue($default_value);
  }

  /** * {@inheritdoc} */
  public function save(array $form, FormStateInterface $form_state) {
    $this->entity->save();

    $this->messenger()->addStatus($this->t('Saved %label configuration.', ['%label' => $this->entity->getLabel()]));

    $request = $this->getRequest();
    


  /** * {@inheritdoc} */
  public function getFieldDefinitions() {
    $definitions = [];

    $definitions['content_translation_source'] = BaseFieldDefinition::create('language')
      ->setLabel(t('Translation source'))
      ->setDescription(t('The source language from which this translation was created.'))
      ->setDefaultValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
      ->setInitialValue(LanguageInterface::LANGCODE_NOT_SPECIFIED)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    $definitions['content_translation_outdated'] = BaseFieldDefinition::create('boolean')
      ->setLabel(t('Translation outdated'))
      ->setDescription(t('A boolean indicating whether this translation needs to be updated.'))
      ->setDefaultValue(FALSE)
      ->setInitialValue(FALSE)
      ->setRevisionable(TRUE)
      ->setTranslatable(TRUE);

    
// The langcode field should always be translatable if the entity type is.       if (isset($keys['langcode']) && isset($base_field_definitions[$keys['langcode']])) {
        $base_field_definitions[$keys['langcode']]->setTranslatable(TRUE);
      }
      // A default_langcode field should always be defined.       if (!isset($base_field_definitions[$keys['default_langcode']])) {
        $base_field_definitions[$keys['default_langcode']] = BaseFieldDefinition::create('boolean')
          ->setLabel($this->t('Default translation'))
          ->setDescription($this->t('A flag indicating whether this is the default translation.'))
          ->setTranslatable(TRUE)
          ->setRevisionable(TRUE)
          ->setDefaultValue(TRUE);
      }
    }

    // Make sure that revisionable entity types are correctly defined.     if ($entity_type->isRevisionable()) {
      $field_name = $entity_type->getRevisionMetadataKey('revision_default');
      $base_field_definitions[$field_name] = BaseFieldDefinition::create('boolean')
        ->setLabel($this->t('Default revision'))
        ->setDescription($this->t('A flag indicating whether this was a default revision when it was saved.'))
        ->setStorageRequired(TRUE)
        ->setInternal(TRUE)
        
/** * Creates an unpublished node and confirms correct redirect behavior. */
  public function testUnpublishedNodeCreation() {
    // Set the front page to the test page.     $this->config('system.site')->set('page.front', '/test-page')->save();

    // Set "Basic page" content type to be unpublished by default.     $fields = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
    $fields['status']->getConfig('page')
      ->setDefaultValue(FALSE)
      ->save();

    // Create a node.     $edit = [];
    $edit['title[0][value]'] = $this->randomMachineName(8);
    $edit['body[0][value]'] = $this->randomMachineName(16);
    $this->drupalGet('node/add/page');
    $this->submitForm($edit, 'Save');

    // Check that the user was redirected to the home page.     $this->assertSession()->addressEquals('');
    
$node = new PrototypedArrayNode('root');
        $prototype = new ArrayNode(null, $node);
        $node->setPrototype($prototype);
        $this->assertEmpty($node->getDefaultValue());
    }

    public function testGetDefaultValueReturnsDefaultValueForPrototypes()
    {
        $node = new PrototypedArrayNode('root');
        $prototype = new ArrayNode(null, $node);
        $node->setPrototype($prototype);
        $node->setDefaultValue(['test']);
        $this->assertEquals(['test']$node->getDefaultValue());
    }

    // a remapped key (e.g. "mapping" -> "mappings") should be unset after being used     public function testRemappedKeysAreUnset()
    {
        $node = new ArrayNode('root');
        $mappingsNode = new PrototypedArrayNode('mappings');
        $node->addChild($mappingsNode);

        // each item under mappings is just a scalar
      // type because it has the 'langcode' entity key defined.       $field_storage_definitions['langcode']->setTranslatable(TRUE);

      $field_storage_definitions['default_langcode'] = BaseFieldDefinition::create('boolean')
        ->setName('default_langcode')
        ->setTargetEntityTypeId('entity_test_update')
        ->setTargetBundle(NULL)
        ->setLabel(new TranslatableMarkup('Default translation'))
        ->setDescription(new TranslatableMarkup('A flag indicating whether this is the default translation.'))
        ->setTranslatable(TRUE)
        ->setRevisionable(TRUE)
        ->setDefaultValue(TRUE);
    }

    if ($revisionable && $translatable) {
      $field_storage_definitions['revision_translation_affected'] = BaseFieldDefinition::create('boolean')
        ->setName('revision_translation_affected')
        ->setTargetEntityTypeId('entity_test_update')
        ->setTargetBundle(NULL)
        ->setLabel(new TranslatableMarkup('Revision translation affected'))
        ->setDescription(new TranslatableMarkup('Indicates if the last edit of a translation belongs to current revision.'))
        ->setReadOnly(TRUE)
        ->setRevisionable(TRUE)
        

  public static function baseFieldDefinitions(EntityTypeInterface $entity_type) {
    $fields = parent::baseFieldDefinitions($entity_type);
    $fields += static::ownerBaseFieldDefinitions($entity_type);

    $fields['name'] = BaseFieldDefinition::create('string')
      ->setLabel(t('Name'))
      ->setRequired(TRUE)
      ->setTranslatable(TRUE)
      ->setRevisionable(TRUE)
      ->setDefaultValue('')
      ->setSetting('max_length', 255)
      ->setDisplayOptions('form', [
        'type' => 'string_textfield',
        'weight' => -5,
      ])
      ->setDisplayConfigurable('form', TRUE)
      ->setDisplayConfigurable('view', TRUE);

    $fields['thumbnail'] = BaseFieldDefinition::create('image')
      ->setLabel(t('Thumbnail'))
      ->setDescription(t('The thumbnail of the media item.'))
      
$this->assertEquals($expected$mock_context_definition->getConstraint($constraint));
  }

  /** * @covers ::getDefaultValue * @covers ::setDefaultValue */
  public function testDefaultValue() {
    $context_definition = new ContextDefinition();
    $this->assertNull($context_definition->getDefaultValue());
    $context_definition->setDefaultValue('test');
    $this->assertSame('test', $context_definition->getDefaultValue());
  }

}
$fields[$entity_type->getRevisionMetadataKey('revision_user')] = BaseFieldDefinition::create('entity_reference')
      ->setLabel(t('Revision user'))
      ->setDescription(t('The user ID of the author of the current revision.'))
      ->setSetting('target_type', 'user')
      ->setRevisionable(TRUE);

    $fields[$entity_type->getRevisionMetadataKey('revision_log_message')] = BaseFieldDefinition::create('string_long')
      ->setLabel(t('Revision log message'))
      ->setDescription(t('Briefly describe the changes you have made.'))
      ->setRevisionable(TRUE)
      ->setDefaultValue('')
      ->setDisplayOptions('form', [
        'type' => 'string_textarea',
        'weight' => 25,
        'settings' => [
          'rows' => 4,
        ],
      ]);

    return $fields;
  }

  
if ($default === 'NULL') {
                $default = null;
            }

            $item = new ConfigurationStruct();
            $item->setTableName($table);
            $item->setColumnName($column->getName());
            $item->setIdentifier($this->tableMapping->isIdentifierColumn($table$column->getName()));
            $item->setCore($this->tableMapping->isCoreColumn($table$column->getName()));
            $item->setColumnType($this->typeMapping->dbalToUnified($column->getType()));
            $item->setElasticSearchType($this->typeMapping->unifiedToElasticSearch($item->getColumnType()));
            $item->setDefaultValue($default);

            if (isset($configuration[$name])) {
                $config = $configuration[$name];
                $item->setId((int) $config['id']);
                $item->setColumnType($config['columnType']);
                $item->setSupportText($config['supportText']);
                $item->setHelpText($config['helpText']);
                $item->setDisplayInBackend((bool) $config['displayInBackend']);
                $item->setReadonly((bool) $config['readonly']);
                $item->setLabel($config['label']);
                $item->setPosition((int) $config['position']);
                

    ]);

    // Create node 2 relying on defaults.     $this->createNode([
      'type' => 'test_node_type',
      'title' => 'Test Node 2 Uses Defaults',
    ]);

    // Add default value to field_string_late_default.     $field = FieldConfig::loadByName('node', 'test_node_type', 'field_string_late_default');
    $field->setDefaultValue('Too late!');
    $field->save();
  }

  /** * Tests display of default field values. */
  public function testDefaultValues() {
    // Begin by viewing nodes with Layout Builder disabled.     $this->assertNodeWithValues();
    $this->assertNodeWithDefaultValues();

    
Home | Imprint | This part of the site doesn't use cookies.