getgrav/grav · error · InvalidArgumentException

Invalid argument $element

Error message

Invalid argument $element

What it means

AbstractIndexCollection::add() appends an element keyed by getCurrentKey($element), and like set() it first runs isAllowedElement(). For Flex collections the element must be a FlexObject instance; anything else (array, scalar, null, foreign object) throws InvalidArgumentException('Invalid argument $element').

Source

Thrown at system/src/Grav/Framework/Collection/AbstractIndexCollection.php:296

    /**
     * {@inheritDoc}
     */
    public function set($key, $value)
    {
        if (!$this->isAllowedElement($value)) {
            throw new InvalidArgumentException('Invalid argument $value');
        }

        $this->entries[$key] = $this->getElementMeta($value);
    }

    /**
     * {@inheritDoc}
     */
    public function add($element)
    {
        if (!$this->isAllowedElement($element)) {
            throw new InvalidArgumentException('Invalid argument $element');
        }

        $this->entries[$this->getCurrentKey($element)] = $this->getElementMeta($element);

        return true;
    }

    /**
     * {@inheritDoc}
     */
    public function isEmpty()
    {
        return empty($this->entries);
    }

    /**
     * Required by interface IteratorAggregate.
     *

View on GitHub (pinned to 6040efed04)

Solutions

  1. Hydrate before adding: convert each row to a FlexObject via the Flex type's create/update API, then add($object).
  2. Null-guard chained lookups: if ($obj = $collection->find($id)) { $index->add($obj); }.
  3. If mixed content is intentional, switch to a non-index collection (ArrayCollection) that imposes no element type.

Example fix

// before
foreach ($jsonRows as $row) {
    $index->add($row); // array -> InvalidArgumentException
}

// after
foreach ($jsonRows as $row) {
    $index->add($flex->createObject($row));
}
Defensive patterns

Strategy: type-guard

Type guard

use Grav\Framework\Flex\FlexObject;

if ($element instanceof FlexObject) {
    $index->add($element);
} elseif (is_array($element)) {
    $index->add($flex->createObject($element)); // hydrate arrays
} else {
    throw new \InvalidArgumentException('Expected FlexObject or row array');
}

Prevention

When it happens

Trigger: Calling $flexIndex->add($arrayFromJson) with decoded raw data; add(null) when a chained lookup returned nothing; porting loops that previously pushed arrays into a plain collection; adding a FlexObject from a different Flex type/collection contract that is not the expected class.

Common situations: Building Flex indexes from external imports (CSV/JSON rows) without hydrating to objects; generic collection utility code shared between ArrayCollection and FlexIndex; null/false propagation from find() calls feeding add().

Related errors


AI-assisted analysis of getgrav/grav@6040efed04 (2026-08-17). Data as JSON: /api/errors/6bccc39c3b7430e2. Report an issue: GitHub.