Provide insertItem ItemList method

Created on 13 December 2020, over 3 years ago
Updated 15 March 2024, 6 months ago

Problem/Motivation

There is no method provided to insert an element into the middle of an ItemList.

Steps to reproduce

Add a Paragraphs field to a content type.
Create a node with several paragraphs added.
Programmatically insert a Paragraph into the middle of the EntityReferenceRevisionsFieldItemList.

Proposed resolution

Provide an insertItem method to ItemList .

It might go something like:

  /**
   * Inserts a new item to the list.
   *
   * @param integer $position
   *   The desired position of the new element to be added.
   * @param mixed $value
   *   The value of the new item.
   * @return \Drupal\Core\TypedData\TypedDataInterface 
   *   The item that was inserted.
   */
  public function insertItem(int $position, $value) {
    // Make a temporary sub-list.
    $definition = $this->getFieldDefinition();
    $name = $this->getName();
    $parent = $this->getParent();
    $tmp = new EntityReferenceRevisionsFieldItemList($definition, $name, $parent);

    // Append our items to the sub-list and insert our new element where needed.
    foreach ($this as $k => $v) {
      if ($k == $position) {
        $tmp->appendItem($value);
      }
      $tmp->appendItem($v->getValue());
    }

    $this->list = $tmp;
    return $this;
  }

This first pass is missing fault tree capture (e.g. position validation, etc).

Remaining tasks

  • Add new method
  • Write Test coverage
  • Write Documentation
  • Write Release note

API changes

Release notes snippet

✨ Feature request
Status

Closed: duplicate

Version

11.0 πŸ”₯

Component
Typed dataΒ  β†’

Last updated 2 days ago

  • Maintained by
  • πŸ‡¦πŸ‡ΉAustria @fago
Created by

πŸ‡ΊπŸ‡ΈUnited States jcandan

Live updates comments and jobs are added and updated live.
Sign in to follow issues

Comments & Activities

Not all content is available!

It's likely this issue predates Contrib.social: some issue and comment data are missing.

Production build 0.71.5 2024