getFieldDefinition example

$timestamp_data_denormalization = $this->randomMachineName();

    $timestamp_item = $this->createTimestampItemProphecy();
    // The field item should get the Timestamp @DataType denormalization set as     // a value, in FieldItemNormalizer::denormalize().     $timestamp_item->setValue(['value' => $timestamp_data_denormalization])
      ->shouldBeCalled();

    // Avoid a static method call by returning dummy serialized property data.     $field_definition = $this->prophesize(FieldDefinitionInterface::class);
    $timestamp_item
      ->getFieldDefinition()
      ->willReturn($field_definition->reveal())
      ->shouldBeCalled();
    $timestamp_item->getPluginDefinition()
      ->willReturn([
        'serialized_property_names' => [
          'foo' => 'bar',
        ],
      ])
      ->shouldBeCalled();
    $entity = $this->prophesize(EntityInterface::class);
    $entity_type = $this->prophesize(EntityTypeInterface::class);
    
// On new revisions, all files are considered to be a new usage and no       // deletion of previous file usages are necessary.       if (!empty($entity->original) && $entity->getRevisionId() != $entity->original->getRevisionId()) {
        foreach ($files as $file) {
          \Drupal::service('file.usage')->add($file, 'file', $entity->getEntityTypeId()$entity->id());
        }
        return;
      }

      // Get the file IDs attached to the field before this update.       $field_name = $this->getFieldDefinition()->getName();
      $original_ids = [];
      $langcode = $this->getLangcode();
      $original = $entity->original;
      if ($original->hasTranslation($langcode)) {
        $original_items = $original->getTranslation($langcode)->{$field_name};
        foreach ($original_items as $item) {
          $original_ids[] = $item->target_id;
        }
      }

      // Decrement file usage by 1 for files that were removed from the field.
// If the entity has not been loaded, create it in memory now.     if (!isset($entity)) {
      $values = [];
      if ($bundle_key = $entity_type->getKey('bundle')) {
        $values[$bundle_key] = $bundle;
      }
      /** @var \Drupal\Core\Entity\FieldableEntityInterface $entity */
      $entity = $storage->create($values);
    }

    $items = $entity->get($field_name);
    $field_definition = $items->getFieldDefinition();

    // Check that the field is an entity reference, or subclass of it, since we     // need to check the target_type setting.     if (!$items instanceof EntityReferenceFieldItemList) {
      throw new \LogicException('Expected the media library to be opened by an entity reference field.');
    }
    if ($field_definition->getFieldStorageDefinition()->getSetting('target_type') !== 'media') {
      throw new \LogicException('Expected the media library to be opened by an entity reference field that target media items.');
    }

    $field_access = $access_handler->fieldAccess('edit', $field_definition$account$items, TRUE);
    

  public function viewElements(FieldItemListInterface $items$langcode) {
    $view_mode = $this->getSetting('view_mode');
    $elements = [];

    foreach ($this->getEntitiesToView($items$langcode) as $delta => $entity) {
      // Due to render caching and delayed calls, the viewElements() method       // will be called later in the rendering process through a '#pre_render'       // callback, so we need to generate a counter that takes into account       // all the relevant information about this field and the referenced       // entity that is being rendered.       $recursive_render_id = $items->getFieldDefinition()->getTargetEntityTypeId()
        . $items->getFieldDefinition()->getTargetBundle()
        . $items->getName()
        // We include the referencing entity, so we can render default images         // without hitting recursive protections.         . $items->getEntity()->id()
        . $entity->getEntityTypeId()
        . $entity->id();

      if (isset(static::$recursiveRenderDepth[$recursive_render_id])) {
        static::$recursiveRenderDepth[$recursive_render_id]++;
      }
      
// Check that the image item can be set to the referenced file directly.     $entity->image_test = $this->image;
    $this->assertEquals($this->image->id()$entity->image_test->target_id);

    // Delete the image and try to save the entity again.     $this->image->delete();
    $entity = EntityTest::create(['name' => $this->randomMachineName()]);
    $entity->save();

    // Test image item properties.     $expected = ['target_id', 'entity', 'alt', 'title', 'width', 'height'];
    $properties = $entity->getFieldDefinition('image_test')->getFieldStorageDefinition()->getPropertyDefinitions();
    $this->assertEquals($expectedarray_keys($properties));

  }

  /** * Tests generateSampleItems() method under different resolutions. */
  public function testImageItemSampleValueGeneration() {

    // Default behaviour. No resolution configuration.     $entity = EntityTest::create();
    

    }

    // Early opt-out if nothing to validate.     if (!$new_entities && !$target_ids) {
      return;
    }

    $entity = !empty($value->getParent()) ? $value->getEntity() : NULL;

    /** @var \Drupal\Core\Entity\EntityReferenceSelection\SelectionInterface $handler * */
    $handler = $this->selectionManager->getSelectionHandler($value->getFieldDefinition()$entity);
    $target_type_id = $value->getFieldDefinition()->getSetting('target_type');

    // Add violations on deltas with a new entity that is not valid.     if ($new_entities) {
      if ($handler instanceof SelectionWithAutocreateInterface) {
        $valid_new_entities = $handler->validateReferenceableNewEntities($new_entities);
        $invalid_new_entities = array_diff_key($new_entities$valid_new_entities);
      }
      else {
        // If the selection handler does not support referencing newly created         // entities, all of them should be invalidated.
$this->assertSame('Rolling Stones', $user->profile_bands[4]->value);
    $this->assertSame('Queen', $user->profile_bands[5]->value);
    $this->assertSame('The White Stripes', $user->profile_bands[6]->value);
    $this->assertSame('1974-06-02', $user->profile_birthdate->value);
    $this->assertSame('http://example.com/blog', $user->profile_blog->uri);
    $this->assertNull($user->profile_blog->title);
    $this->assertSame([]$user->profile_blog->options);
    $this->assertSame('http://example.com/blog', $user->profile_blog->uri);

    // Check that the source profile field names that are longer than 32     // characters have been migrated.     $this->assertNotNull($user->getFieldDefinition('profile_really_really_love_mig'));
    $this->assertNotNull($user->getFieldDefinition('profile_really_really_love_mig1'));
    $this->assertSame('1', $user->profile_really_really_love_mig->value);
    $this->assertNull($user->profile_really_really_love_mig1->value);

    $user = User::load(8);
    $this->assertSame('Forward/slash', $user->profile_sold_to->value);

    $user = User::load(15);
    $this->assertSame('Dot.in.the.middle', $user->profile_sold_to->value);
  }

}
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'),
            
// We only output a link if we are certain that users will get the       // permission to post comments by logging in.       $this->authenticatedCanPostComments = $this->entityTypeManager
        ->getStorage('user_role')
        ->load(RoleInterface::AUTHENTICATED_ID)
        ->hasPermission('post comments');
    }

    if ($this->authenticatedCanPostComments) {
      // We cannot use the redirect.destination service here because these links       // sometimes appear on /node and taxonomy listing pages.       if ($entity->get($field_name)->getFieldDefinition()->getSetting('form_location') == CommentItemInterface::FORM_SEPARATE_PAGE) {
        $comment_reply_parameters = [
          'entity_type' => $entity->getEntityTypeId(),
          'entity' => $entity->id(),
          'field_name' => $field_name,
        ];
        $destination = ['destination' => Url::fromRoute('comment.reply', $comment_reply_parameters['fragment' => 'comment-form'])->toString()];
      }
      else {
        $destination = ['destination' => $entity->toUrl('canonical', ['fragment' => 'comment-form'])->toString()];
      }

      

  public function testBlockAccessEntityAllowedFieldHasValue($expected$is_empty$default_value) {
    $entity = $this->prophesize(FieldableEntityInterface::class);
    $block = $this->getTestBlock($entity);

    $account = $this->prophesize(AccountInterface::class);
    $entity->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());
    $entity->hasField('the_field_name')->willReturn(TRUE);
    $field = $this->prophesize(FieldItemListInterface::class);
    $field_definition = $this->prophesize(FieldDefinitionInterface::class);
    $field->getFieldDefinition()->willReturn($field_definition->reveal());
    $field_definition->getDefaultValue($entity->reveal())->willReturn($default_value);
    $field_definition->getType()->willReturn('not_an_image');
    $entity->get('the_field_name')->willReturn($field->reveal());

    $field->access('view', $account->reveal(), TRUE)->willReturn(AccessResult::allowed());
    $field->isEmpty()->willReturn($is_empty)->shouldBeCalled();

    $access = $block->access($account->reveal(), TRUE);
    $this->assertSame($expected$access->isAllowed());
  }

  
public function getSettableValues(AccountInterface $account = NULL) {
    // Flatten options firstly, because Settable Options may contain group     // arrays.     $flatten_options = OptGroup::flattenOptions($this->getSettableOptions($account));
    return array_keys($flatten_options);
  }

  /** * {@inheritdoc} */
  public function getSettableOptions(AccountInterface $account = NULL) {
    $allowed_options = options_allowed_values($this->getFieldDefinition()->getFieldStorageDefinition()$this->getEntity());
    return $allowed_options;
  }

  /** * {@inheritdoc} */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $allowed_options = options_allowed_values($field_definition->getFieldStorageDefinition());
    if (empty($allowed_options)) {
      $values['value'] = NULL;
      return $values;
    }
/** * {@inheritdoc} */
  public function getLangcode() {
    return $this->getParent()->getLangcode();
  }

  /** * {@inheritdoc} */
  public function getFieldDefinition() {
    return $this->definition->getFieldDefinition();
  }

  /** * Returns the array of field settings. * * @return array * The array of settings. */
  protected function getSettings() {
    return $this->getFieldDefinition()->getSettings();
  }

  
public function testNormalize($parent_field_item_class$datetime_type$expected_format) {
    $formatted_string = $this->randomMachineName();

    $field_item = $this->prophesize($parent_field_item_class);
    if ($parent_field_item_class === DateTimeItem::class) {
      $field_storage_definition = $this->prophesize(FieldStorageDefinitionInterface::class);
      $field_storage_definition->getSetting('datetime_type')
        ->willReturn($datetime_type);
      $field_definition = $this->prophesize(FieldDefinitionInterface::class);
      $field_definition->getFieldStorageDefinition()
        ->willReturn($field_storage_definition);
      $field_item->getFieldDefinition()
        ->willReturn($field_definition);
    }
    else {
      $field_item->getFieldDefinition(Argument::any())
        ->shouldNotBeCalled();
    }
    $this->data->getParent()
      ->willReturn($field_item);

    $drupal_date_time = $this->prophesize(DateTimeIso8601NormalizerTestDrupalDateTime::class);
    $drupal_date_time->setTimezone(new \DateTimeZone('Australia/Sydney'))
      
return FALSE;
  }

  /** * {@inheritdoc} */
  public function getConstraints() {
    $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
    $constraints = parent::getConstraints();

    $settings = $this->getSettings();
    $label = $this->getFieldDefinition()->getLabel();

    if (isset($settings['min']) && $settings['min'] !== '') {
      $min = $settings['min'];
      $constraints[] = $constraint_manager->create('ComplexData', [
        'value' => [
          'Range' => [
            'min' => $min,
            'minMessage' => $this->t('%name: the value may be no less than %min.', ['%name' => $label, '%min' => $min]),
          ],
        ],
      ]);
    }
->shouldBeCalled();

    $entity_reference = $this->prophesize(TypedDataInterface::class);
    $entity_reference->getValue()
      ->willReturn($entity->reveal())
      ->shouldBeCalled();

    $field_definition = $this->prophesize(FieldDefinitionInterface::class);
    $field_definition->getSetting('target_type')
      ->willReturn('test_type');

    $this->fieldItem->getFieldDefinition()
      ->willReturn($field_definition->reveal());

    $this->fieldItem->get('entity')
      ->willReturn($entity_reference)
      ->shouldBeCalled();

    $this->fieldItem->getProperties(TRUE)
      ->willReturn(['target_id' => $this->getTypedDataProperty(FALSE)])
      ->shouldBeCalled();

    $normalized = $this->normalizer->normalize($this->fieldItem->reveal());

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