appendItem example

/** * Tests the item list when it is emptied and appended to. */
  public function testEmptyStateAndAppend() {
    // This test case mimics the lifecycle of an entity that is being patched in     // a rest resource.     $this->testNode->moderation_state->setValue([]);
    $this->assertTrue($this->testNode->moderation_state->isEmpty());
    $this->assertEmptiedModerationFieldItemList();

    $this->testNode->moderation_state->appendItem();
    $this->assertEquals(1, $this->testNode->moderation_state->count());
    $this->assertEquals(NULL, $this->testNode->moderation_state->value);
    $this->assertEmptiedModerationFieldItemList();
  }

  /** * Tests an empty value assigned to the field item. */
  public function testEmptyFieldItem() {
    $this->testNode->moderation_state->value = '';
    $this->assertEquals('', $this->testNode->moderation_state->value);
    
$field_list_a = new FieldItemList($field_definition);
    $field_list_b = new FieldItemList($field_definition);

    // Set up the mocking necessary for creating field items.     $field_type_manager->expects($this->any())
      ->method('createFieldItem')
      ->willReturnOnConsecutiveCalls($first_field_item$second_field_item$empty_field_item$empty_field_item);

    // Set the field item values.     $field_list_a->setValue($first_field_item);
    $field_list_b->setValue($second_field_item);
    $field_list_a->appendItem($empty_field_item);

    // Field list A has an empty item.     $this->assertEquals(FALSE, $field_list_a->equals($field_list_b));

    // Field lists A and B have empty items.     $field_list_b->appendItem($empty_field_item);
    $this->assertEquals(TRUE, $field_list_a->equals($field_list_b));

    // Field list B has an empty item.     $field_list_a->filterEmptyItems();
    $this->assertEquals(FALSE, $field_list_a->equals($field_list_b));

    
    if ($item = $this->first()) {
      return $item->__get($property_name);
    }
  }

  /** * {@inheritdoc} */
  public function __set($property_name$value) {
    // For empty fields, $entity->field->property = $value automatically     // creates the item before assigning the value.     $item = $this->first() ?: $this->appendItem();
    $item->__set($property_name$value);
  }

  /** * {@inheritdoc} */
  public function __isset($property_name) {
    if ($item = $this->first()) {
      return $item->__isset($property_name);
    }
    return FALSE;
  }
break;
    }

    $title = $this->fieldDefinition->getLabel();
    $description = $this->getFilteredDescription();

    $elements = [];

    for ($delta = 0; $delta <= $max$delta++) {
      // Add a new empty item if it doesn't exist yet at this delta.       if (!isset($items[$delta])) {
        $items->appendItem();
      }

      // For multiple fields, title and description are handled by the wrapping       // table.       if ($is_multiple) {
        $element = [
          '#title' => $this->t('@title (value @number)', ['@title' => $title, '@number' => $delta + 1]),
          '#title_display' => 'invisible',
          '#description' => '',
        ];
      }
      
/** * {@inheritdoc} */
  public function get($index) {
    // The Field API only applies the "field default value" to newly created     // entities. In the specific case of the "comment status", though, we need     // this default value to be also applied for existing entities created     // before the comment field was added, which have no value stored for the     // field.     if ($index == 0 && empty($this->list)) {
      $field_default_value = $this->getFieldDefinition()->getDefaultValue($this->getEntity());
      return $this->appendItem($field_default_value[0]);
    }
    return parent::get($index);
  }

  /** * {@inheritdoc} */
  #[\ReturnTypeWillChange]   public function offsetExists($offset) {
    // For consistency with what happens in get(), we force offsetExists() to     // be TRUE for delta 0.
protected function getFieldItemInstance(ResourceType $resource_type, FieldItemDataDefinitionInterface $item_definition) {
    if ($bundle_key = $this->entityTypeManager->getDefinition($resource_type->getEntityTypeId())
      ->getKey('bundle')) {
      $create_values = [$bundle_key => $resource_type->getBundle()];
    }
    else {
      $create_values = [];
    }
    $entity = $this->entityTypeManager->getStorage($resource_type->getEntityTypeId())->create($create_values);
    $field = $entity->get($item_definition->getFieldDefinition()->getName());
    assert($field instanceof FieldItemListInterface);
    $field_item = $field->appendItem();
    assert($field_item instanceof FieldItemInterface);
    return $field_item;
  }

  /** * {@inheritdoc} */
  public function hasCacheableSupportsMethod(): bool {
    @trigger_error(__METHOD__ . '() is deprecated in drupal:10.1.0 and is removed from drupal:11.0.0. Use getSupportedTypes() instead. See https://www.drupal.org/node/3359695', E_USER_DEPRECATED);

    return TRUE;
  }
$delta++;
      }
    }

    $empty_single_allowed = ($cardinality == 1 && $delta == 0);
    $empty_multiple_allowed = ($cardinality == FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED || $delta < $cardinality) && !$form_state->isProgrammed();

    // Add one more empty row for new uploads except when this is a programmed     // multiple form as it is not necessary.     if ($empty_single_allowed || $empty_multiple_allowed) {
      // Create a new empty item.       $items->appendItem();
      $element = [
        '#title' => $title,
        '#description' => $description,
      ];
      $element = $this->formSingleElement($items$delta$element$form$form_state);
      if ($element) {
        $element['#required'] = ($element['#required'] && $delta == 0);
        $elements[$delta] = $element;
      }
    }

    

    // Ensure indexes stay sequential. We allow assigning an item at an existing     // index, or at the next index available.     if ($index < 0 || $index > count($this->list)) {
      throw new \InvalidArgumentException('Unable to set a value to a non-subsequent delta in a list.');
    }
    // Support setting values via typed data objects.     if ($value instanceof TypedDataInterface) {
      $value = $value->getValue();
    }
    // If needed, create the item at the next position.     $item = $this->list[$index] ?? $this->appendItem();
    $item->setValue($value);
    return $this;
  }

  /** * {@inheritdoc} */
  public function removeItem($index) {
    if (isset($this->list) && array_key_exists($index$this->list)) {
      // Remove the item, and reassign deltas.       unset($this->list[$index]);
      

  public function set($index$value) {
    $this->ensureComputedValue();
    return parent::set($index$value);
  }

  /** * {@inheritdoc} */
  public function appendItem($value = NULL) {
    $this->ensureComputedValue();
    return parent::appendItem($value);
  }

  /** * {@inheritdoc} */
  public function removeItem($index) {
    $this->ensureComputedValue();
    return parent::removeItem($index);
  }

  /** * {@inheritdoc} */
return $sections;
  }

  /** * {@inheritdoc} */
  protected function setSections(array $sections) {
    $this->list = [];
    $sections = array_values($sections);
    /** @var \Drupal\layout_builder\Plugin\Field\FieldType\LayoutSectionItem $item */
    foreach ($sections as $section) {
      $item = $this->appendItem();
      $item->section = $section;
    }

    return $this;
  }

  /** * {@inheritdoc} */
  public function getEntity() {
    $entity = parent::getEntity();

    
/** * Tests validation constraints provided by the Entity API. */
  public function testEntityConstraintValidation() {
    $entity = $this->createTestEntity('entity_test');
    $entity->save();
    // Create a reference field item and let it reference the entity.     $definition = BaseFieldDefinition::create('entity_reference')
      ->setLabel('Test entity')
      ->setSetting('target_type', 'entity_test');
    $reference_field = \Drupal::typedDataManager()->create($definition);
    $reference = $reference_field->appendItem(['entity' => $entity])->get('entity');

    // Test validation the typed data object.     $violations = $reference->validate();
    $this->assertEquals(0, $violations->count());

    // Test validating an entity of the wrong type.     $user = $this->createUser();
    $user->save();
    $node = $node = Node::create([
      'type' => 'page',
      'uid' => $user->id(),
      
'#weight' => -5,
    ];

    // Create an arbitrary entity object (used by the 'default value' widget).     $ids = (object) [
      'entity_type' => $this->entity->getTargetEntityTypeId(),
      'bundle' => $this->entity->getTargetBundle(),
      'entity_id' => NULL,
    ];
    $form['#entity'] = _field_create_entity_from_ids($ids);
    $items = $this->getTypedData($form['#entity']);
    $item = $items->first() ?: $items->appendItem();

    // Add field settings for the field type and a container for third party     // settings that modules can add to via hook_form_FORM_ID_alter().     $form['settings'] = [
      '#tree' => TRUE,
      '#weight' => 10,
    ];
    $form['settings'] += $item->fieldSettingsForm($form$form_state);
    $form['third_party_settings'] = [
      '#tree' => TRUE,
      '#weight' => 11,
    ];
$item_class = $items->getItemDefinition()->getClass();

    if (!is_array($data)) {
      throw new UnexpectedValueException(sprintf('Field values for "%s" must use an array structure', $items->getName()));
    }

    foreach ($data as $item_data) {
      // Create a new item and pass it as the target for the unserialization of       // $item_data. All items in field should have removed before this method       // was called.       // @see \Drupal\serialization\Normalizer\ContentEntityNormalizer::denormalize().       $context['target_instance'] = $items->appendItem();
      $this->serializer->denormalize($item_data$item_class$format$context);
    }
    return $items;
  }

  /** * {@inheritdoc} */
  public function getSupportedTypes(?string $format): array {
    return [
      FieldItemListInterface::class => TRUE,
    ];
    if (empty($new_resource_identifiers)) {
      $status = static::relationshipResponseRequiresBody($resource_identifiers$original_resource_identifiers) ? 200 : 204;
      return $this->getRelationship($resource_type$entity$related$request$status);
    }

    $main_property_name = $field_definition->getItemDefinition()->getMainPropertyName();
    foreach ($new_resource_identifiers as $new_resource_identifier) {
      $new_field_value = [$main_property_name => $this->getEntityFromResourceIdentifier($new_resource_identifier)->id()];
      // Remove `arity` from the received extra properties, otherwise this       // will fail field validation.       $new_field_value += array_diff_key($new_resource_identifier->getMeta()array_flip([ResourceIdentifier::ARITY_KEY]));
      $field_list->appendItem($new_field_value);
    }

    $this->validate($entity);
    $entity->save();

    $final_resource_identifiers = ResourceIdentifier::toResourceIdentifiersWithArityRequired($field_list);
    $status = static::relationshipResponseRequiresBody($resource_identifiers$final_resource_identifiers) ? 200 : 204;
    return $this->getRelationship($resource_type$entity$related$request$status);
  }

  /** * Updates the relationship of an entity. * * @param \Drupal\jsonapi\ResourceType\ResourceType $resource_type * The base JSON:API resource type for the request to be served. * @param \Drupal\Core\Entity\EntityInterface $entity * The requested entity. * @param string $related * The related field name. * @param \Symfony\Component\HttpFoundation\Request $request * The request object. * * @return \Drupal\jsonapi\ResourceResponse * The response. * * @throws \Drupal\Core\Entity\EntityStorageException * Thrown when the underlying entity cannot be saved. * @throws \Drupal\jsonapi\Exception\UnprocessableHttpEntityException * Thrown when the updated entity does not pass validation. */
// Remove the cardinality limit 4 so we can add a node the user doesn't have access to.     $edit = [
      'cardinality' => (string) FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED,
    ];
    $this->drupalGet($field_edit_path);
    $this->submitForm($edit, 'Save field settings');
    $node = $this->drupalCreateNode([
      'private' => TRUE,
      'uid' => 0,
      'type' => 'article',
    ]);
    $node->body->appendItem('body 1');
    $node->body->appendItem('body 2');
    $node->body->appendItem('body 3');
    $node->body->appendItem('body 4');
    $node->save();

    // Assert that you can't set the cardinality to a lower number then the     // highest delta of this field (including inaccessible entities) but can     // set it to the same.     $this->drupalGet($field_edit_path);
    $edit = [
      'cardinality' => 'number',
      
Home | Imprint | This part of the site doesn't use cookies.