getFieldDefinitions example

$form_state = new FormState();
    $form_state->setValues([
      'label' => 'Test type',
      'id' => $source_plugin_id,
      'op' => 'Save',
    ]);

    /** @var \Drupal\Core\Entity\EntityFieldManagerInterface $field_manager */
    $field_manager = \Drupal::service('entity_field.manager');

    // Source field not created yet.     $fields = $field_manager->getFieldDefinitions('media', $source_plugin_id);
    $this->assertArrayNotHasKey($field_name$fields);

    \Drupal::formBuilder()->submitForm($form$form_state);

    // Source field exists now.     $fields = $field_manager->getFieldDefinitions('media', $source_plugin_id);
    $this->assertArrayHasKey($field_name$fields);
  }

}
if ($entity->hasField($field_name)) {
          $edited_fields[] = $field_name;
        }
      }
      $edited_fields = array_unique($edited_fields);
    }
    else {
      $edited_fields = $this->getEditedFieldNames($form_state);
    }

    // Remove violations for fields that are not edited.     $violations->filterByFields(array_diff(array_keys($entity->getFieldDefinitions())$edited_fields));

    $this->flagViolations($violations$form$form_state);

    // The entity was validated.     $entity->setValidationRequired(FALSE);
    $form_state->setTemporaryValue('entity_validated', TRUE);

    return $entity;
  }

  /** * Gets the names of all fields edited in the form. * * If the entity form customly adds some fields to the form (i.e. without * using the form display), it needs to add its fields here and override * flagViolations() for displaying the violations. * * @param \Drupal\Core\Form\FormStateInterface $form_state * The current state of the form. * * @return string[] * An array of field names. */
    $edit = ['language_interface[enabled][language-url]' => 1];
    $this->drupalGet('admin/config/regional/language/detection');
    $this->submitForm($edit, 'Save settings');
    $edit = ['prefix[en]' => 'en'];
    $this->drupalGet('admin/config/regional/language/detection/url');
    $this->submitForm($edit, 'Save configuration');

    // Reset the cache after changing the negotiation settings as that changes     // how links are built.     $this->resetAll();

    $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'page');
    $this->assertTrue($definitions['path']->isTranslatable(), 'Node path is translatable.');
    $this->assertTrue($definitions['body']->isTranslatable(), 'Node body is translatable.');
  }

  /** * Creates content with a link field pointing to an alias of another language. * * @dataProvider providerLanguage */
  public function testLinkTranslationWithAlias($source_langcode) {
    $source_url_options = [
      
'#tree' => TRUE,
      'description' => [
        '#markup' => '<p>' . $this->t('Media sources can provide metadata fields such as title, caption, size information, credits, etc. Media can automatically save this metadata information to entity fields, which can be configured below. Information will only be mapped if the entity field is empty.') . '</p>',
      ],
    ];

    if (empty($source) || empty($source->getMetadataAttributes())) {
      $form['source_dependent']['field_map']['#access'] = FALSE;
    }
    else {
      $options = [MediaSourceInterface::METADATA_FIELD_EMPTY => $this->t('- Skip field -')];
      foreach ($this->entityFieldManager->getFieldDefinitions('media', $this->entity->id()) as $field_name => $field) {
        if (!($field instanceof BaseFieldDefinition) || $field_name === 'name') {
          $options[$field_name] = $field->getLabel();
        }
      }

      natcasesort($options);

      $field_map = $this->entity->getFieldMap();
      foreach ($source->getMetadataAttributes() as $metadata_attribute_name => $metadata_attribute_label) {
        $form['source_dependent']['field_map'][$metadata_attribute_name] = [
          '#type' => 'select',
          


  /** * Tests that the entity_id field is set correctly for each comment bundle. */
  public function testEntityIdField() {
    $field_definitions = [];

    foreach (array_keys($this->targetEntityTypes) as $id) {
      $bundle = 'comment_on_' . $id;
      $field_definitions[$bundle] = $this->entityFieldManager
        ->getFieldDefinitions('comment', $bundle);
    }
    // Test that the value of the entity_id field for each bundle is correct.     foreach ($field_definitions as $bundle => $definition) {
      $entity_type_id = str_replace('comment_on_', '', $bundle);
      $target_type = $definition['entity_id']->getSetting('target_type');
      $this->assertEquals($entity_type_id$target_type);

      // Verify that the target type remains correct       // in the deeply-nested object properties.       $nested_target_type = $definition['entity_id']->getItemDefinition()->getFieldDefinition()->getSetting('target_type');
      $this->assertEquals($entity_type_id$nested_target_type);
    }


    $violations = $entity->validate();

    // Remove violations of inaccessible fields as they cannot stem from our     // changes.     $violations->filterByFieldAccess();

    // Filter violations based on the given fields.     if ($field_names !== NULL) {
      $violations->filterByFields(
        array_diff(array_keys($entity->getFieldDefinitions())$field_names)
      );
    }

    if (count($violations) > 0) {
      // Instead of returning a generic 400 response we use the more specific       // 422 Unprocessable Entity code from RFC 4918. That way clients can       // distinguish between general syntax errors in bad serializations (code       // 400) and semantic errors in well-formed requests (code 422).       // @see \Drupal\jsonapi\Normalizer\UnprocessableHttpEntityExceptionNormalizer       $exception = new UnprocessableHttpEntityException();
      $exception->setViolations($violations);
      
$entity_type = $entity->getEntityType();

    // A list of known revision metadata fields which should be skipped from     // the comparison.     $fields = [
      $entity_type->getKey('revision'),
      $entity_type->getKey('revision_translation_affected'),
    ];
    $fields = array_merge($fieldsarray_values($entity_type->getRevisionMetadataKeys()));

    // Computed fields should be skipped by the check for translation changes.     foreach (array_diff_key($entity->getFieldDefinitions()array_flip($fields)) as $field_name => $field_definition) {
      if ($field_definition->isComputed()) {
        $fields[] = $field_name;
      }
    }

    return $fields;
  }

}


  /** * Executes the introspection tests for the given entity type. * * @param string $entity_type * The entity type to run the tests with. */
  protected function doTestIntrospection($entity_type) {
    // Test getting metadata upfront. The entity types used for this test have     // a default bundle that is the same as the entity type.     $definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions($entity_type$entity_type);
    $this->assertEquals('string', $definitions['name']->getType()$entity_type . ': Name field found.');
    $this->assertEquals('entity_reference', $definitions['user_id']->getType()$entity_type . ': User field found.');
    $this->assertEquals('text', $definitions['field_test_text']->getType()$entity_type . ': Test-text-field field found.');

    // Test deriving further metadata.     $this->assertInstanceOf(FieldDefinitionInterface::class$definitions['name']);
    $field_item_definition = $definitions['name']->getItemDefinition();
    $this->assertInstanceOf(ComplexDataDefinitionInterface::class$field_item_definition);
    $this->assertEquals('field_item:string', $field_item_definition->getDataType());
    $value_definition = $field_item_definition->getPropertyDefinition('value');
    $this->assertInstanceOf(DataDefinitionInterface::class$value_definition);
    
$user = $this->createUser();

    // Create a test entity.     $entity = EntityTestMul::create([
      'name' => $this->randomString(),
      'user_id' => $user->id(),
      'language' => 'en',
    ]);

    $entity->addTranslation('de');
    $entity->save();
    $fields = array_keys($entity->getFieldDefinitions());

    // Reload the entity, clone it and check that both entity objects reference     // different field instances.     $entity = $this->reloadEntity($entity);
    $clone = clone $entity;

    $different_references = TRUE;
    foreach ($fields as $field_name) {
      if ($entity->get($field_name) === $clone->get($field_name)) {
        $different_references = FALSE;
      }
    }
if ($entity_type instanceof ConfigEntityTypeInterface) {
      // The '_core' key is reserved by Drupal core to handle complex edge cases       // correctly. Data in the '_core' key is irrelevant to clients reading       // configuration, and is not allowed to be set by clients writing       // configuration: it is for Drupal core only, and managed by Drupal core.       // @see https://www.drupal.org/node/2653358       $fields['_core'] = new ResourceTypeAttribute('_core', NULL, FALSE);
    }

    $is_fieldable = $entity_type->entityClassImplements(FieldableEntityInterface::class);
    if ($is_fieldable) {
      $field_definitions = $this->entityFieldManager->getFieldDefinitions($entity_type->id()$bundle);
    }

    // For all other fields, use their internal field name also as their public     // field name. Unless they're called "id" or "type": those names are     // reserved by the JSON:API spec.     // @see http://jsonapi.org/format/#document-resource-object-fields     $reserved_field_names = ['id', 'type'];
    foreach (array_diff($field_namesarray_keys($fields)) as $field_name) {
      $alias = $field_name;
      // Alias the fields reserved by the JSON:API spec with `{entity_type}_`.       if (in_array($field_name$reserved_field_names, TRUE)) {
        
if (empty($field_map[$this->entityTypeId][$field_name]['bundles'])) {
      return [];
    }
    $bundles = $field_map[$this->entityTypeId][$field_name]['bundles'];

    // 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,
      
$this->clickLink('block type creation page');

    // Create a block type via the user interface.     $edit = [
      'id' => 'foo',
      'label' => 'title for foo',
    ];
    $this->submitForm($edit, 'Save');
    $block_type = BlockContentType::load('foo');
    $this->assertInstanceOf(BlockContentType::class$block_type);

    $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('block_content', 'foo');
    $this->assertTrue(isset($field_definitions['body']), 'Body field created when using the UI to create block content types.');

    // Check that the block type was created in site default language.     $default_langcode = \Drupal::languageManager()->getDefaultLanguage()->getId();
    $this->assertEquals($block_type->language()->getId()$default_langcode);

    // Create block types programmatically.     $this->createBlockContentType('basic', TRUE);
    $field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('block_content', 'basic');
    $this->assertTrue(isset($field_definitions['body']), "Body field for 'basic' block type created when using the testing API to create block content types.");

    
$form['content_translation']['created']['#access'] = FALSE;
    }

    $form_object = $form_state->getFormObject();
    $form_langcode = $form_object->getFormLangcode($form_state);
    $translations = $entity->getTranslationLanguages();
    $status_translatable = NULL;
    // Change the submit button labels if there was a status field they affect     // in which case their publishing / unpublishing may or may not apply     // to all translations.     if (!$entity->isNew() && (!isset($translations[$form_langcode]) || count($translations) > 1)) {
      foreach ($entity->getFieldDefinitions() as $property_name => $definition) {
        if ($property_name == 'status') {
          $status_translatable = $definition->isTranslatable();
        }
      }
      if (isset($status_translatable)) {
        if (isset($form['actions']['submit'])) {
          $form['actions']['submit']['#value'] .= ' ' . ($status_translatable ? t('(this translation)') : t('(all translations)'));
        }
      }
    }
  }

  
// Reset the index.     $this->index = NULL;
    // Reset history.     $this->history = [];
  }

  /** * {@inheritdoc} */
  public function checkNodeType(NodeInterface $node) {
    // Fetch information about the forum field.     $field_definitions = $this->entityFieldManager->getFieldDefinitions('node', $node->bundle());
    return !empty($field_definitions['taxonomy_forums']);
  }

  /** * {@inheritdoc} */
  public function unreadTopics($term$uid) {
    $query = $this->connection->select('node_field_data', 'n');
    $query->join('forum', 'f', '[n].[vid] = [f].[vid] AND [f].[tid] = :tid', [':tid' => $term]);
    $query->leftJoin('history', 'h', '[n].[nid] = [h].[nid] AND [h].[uid] = :uid', [':uid' => $uid]);
    $query->addExpression('COUNT([n].[nid])', 'count');
    
    // selected above, then we only search for taxonomy fields associated     // with that bundle. Otherwise, we use all bundles.     $bundles = array_keys($this->bundleInfoService->getBundleInfo($this->entityTypeId));
    // Double check that this is a real bundle before using it (since above     // we added a dummy option 'all' to the bundle list on the form).     if (isset($selected_bundle) && in_array($selected_bundle$bundles)) {
      $bundles = [$selected_bundle];
    }
    $tag_fields = [];
    foreach ($bundles as $bundle) {
      $display = $this->entityDisplayRepository->getFormDisplay($this->entityTypeId, $bundle);
      $taxonomy_fields = array_filter($this->entityFieldManager->getFieldDefinitions($this->entityTypeId, $bundle)function DFieldDefinitionInterface $field_definition) {
        return $field_definition->getType() == 'entity_reference' && $field_definition->getSetting('target_type') == 'taxonomy_term';
      });
      foreach ($taxonomy_fields as $field_name => $field) {
        $widget = $display->getComponent($field_name);
        // We define "tag-like" taxonomy fields as ones that use the         // "Autocomplete (Tags style)" widget.         if (!empty($widget) && $widget['type'] == 'entity_reference_autocomplete_tags') {
          $tag_fields[$field_name] = $field;
        }
      }
    }
    
Home | Imprint | This part of the site doesn't use cookies.