Skip to content

[5.x]: Fix Typed property craft\base\FieldLayoutComponent::$elementType must not be accessed before initialization error with Kint and element queries #15074

@engram-design

Description

@engram-design

What happened?

Refer to verbb/kint#8 but since Craft 5, the plugin cannot dump ElementQuery objects anymore. This is due to an error: Typed property craft\base\FieldLayoutComponent::$elementType must not be accessed before initialization.

To reproduce this, add an Entries field to an Entry, then use Kint to output the ElementQuery (not an element collection or single element): {{ d(craft.entries.id(123).one().entriesField) }}

Disregarding the Kint factor here, I feel like this might be a Craft issue.

Taking a deep-dive into things, this seems to be due to the craft\fieldlayoutelements\CustomField (our Entries field) doesn't have an elementType associated with it yet. It's also during this investigation that I've found when settings elements on a FieldLayoutTab that it's own elementType isn't set.

I'm not 110% sure, but shouldn't the elementType for the FieldLayoutTab and resulting CustomField objects be inherited from the FieldLayout::type property? The element type that the field layout is for?

public function setElements(array $elements): void
{
    $fieldsService = Craft::$app->getFields();
    $pluginsService = Craft::$app->getPlugins();
    $this->_elements = [];

+    // Set the element type based on the field layout's element type
+    $this->elementType = $this->layout->type;
+
    foreach ($elements as $layoutElement) {
        if (is_array($layoutElement)) {
            try {
+               // Ensure that layout elements know which element type this is for
+               $layoutElement['elementType'] = $this->elementType;
                $layoutElement = $fieldsService->createLayoutElement($layoutElement);

Which seems to fix my issue. I didn't do a PR, purely because I'm not really sure if this is right, expected behaviour or otherwise.

Craft CMS version

5.1.7

PHP version

8.2.0

Operating system and version

MacOS 14.1

Database type and version

MySQL 8

Image driver and version

No response

Installed plugins and versions

  • Kint 4

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions