Skip to content

[5.x]: Matrix fields with "card" or "element index" view do not fire "afterInit" Garnish event like regular "block" fields #15470

@timmyomahony

Description

@timmyomahony

What happened?

Description

On the Craft 5 control panel entry page, when a Matrix field with the "block" view is rendered, its JavaScript (MatrixInput.js) fires a afterInit event once the field is ready. This is useful for hooking into Matrix fields in JavaScript to augment their functionality.

But when you change the view to use the new "card" or "element index" view (which uses NestedElementManager.js), this event doesn't exist.

This means you can't rely on the afterInit event for Matrix fields, as it only fires for one "view" (the block view).

To fix this, a trigger('afterInit') needs to be added to the NestedElementManager.init function here:

https://github.com/craftcms/cms/blob/5.x/src/web/assets/cp/src/js/NestedElementManager.js#L24

Steps to reproduce

Create some Javascript on the Control Panel that listens for afterInit:

// Works when view = block on matrix field
Garnish.on(
  Craft.MatrixInput,
  "afterInit",
  {},
  function (ev) {
    console.log("Matrix field loaded");
  }.bind(this)
);

// Should work when view = card/element index on matrix field but doesn't
Garnish.on(
  Craft.NestedElementManager,
  "afterInit",
  {},
  function (ev) {
    console.log("Nested matrix field loaded");
  }.bind(this)
)

Expected behavior

When a matrix field input that has its view set as "card" or "element index" loads on the control panel entry page, we should be able to see the console output "Nested matrix field loaded".

Actual behavior

The event afterInit doesn't exist on this field, so it will never run.

Craft CMS version

5

PHP version

No response

Operating system and version

No response

Database type and version

No response

Image driver and version

No response

Installed plugins and versions

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