I need to populate a matrix block field with JavaScript in the control panel. I've got the data ready, but i can't figure out how to add it.

I've located a function called addBlock() in MatrixInput.js but I can not figure out how to call it from my JS code. I've explored both the global Craft and Garnish - without finding the function. I could recreate the entire html of the element, but that seems unnecessary when there are helper functions that I could reach for.

Looks like craft is creating one var for each block available on the page with the following code:

var matrixInput = new Craft.MatrixInput("...")
var matrixInput = new Craft.MatrixInput("...")

It would also be great to have the arguments that needs to be passed to the function - is there any documentation or anyone who struggled with this previously that can point me in the right direction?

1 Answer 1


This is not documented because the P&T team sees this as internal functionality I guess.

Looks like the control panel is going to be rebuilt in version 4 anyways probably in Vue. So you would have to rewrite your entire script too. If it‘s going to be Vue there is probably no way to use their JS API anyways.

Even if it sounds funky I would suggest you to imitate the user input with JS. Just crawl the DOM for the buttons and inputs and fire click and input events on these. This way you could even provide meaningful error messages in the console for yourself, for example if some button selector stopped working after a Craft update because maybe they changed the markup.

As an alternative solution I see a PHP script that populates the entry before rendering it in the entry edit view. However I don’t know if there is an event in Craft where you could hook into the right place.

  • Yeah, the imitation might work. I just know the JS-object is there somewhere in the DOM ready for me to utilize.. I'll give the imitation a shot.
    – Jørgen
    Apr 5, 2021 at 7:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.