How Magento passes server data to minicart.js

If you have ever build some admin grids that would list some entity data, you may have come across Data Sources. Magento recognizes the need to have a separate “channel” to be able to pass any server data into the java script objects and uses this Data Sources heavily in the admin section.

But, at the end of the day, its java script and if you want to make a variable available, you could always add it to the window object and all other js objects will have access to it.
Not ideal, but practical for sure!

In fact this is how its done in the original code:

https://gist.github.com/marjan7790/fba5c72f16a118cc66f60d7cc1fd67f2

Where is the checkout object set? Lets try common sense again! šŸ™‚

It should be part of the checkout module, and it would be probably in a .pthml file. So, ask your favorite IDE to search in the vendor/magento/module-checkout folder for phrases like “window.checkout =”. Restrict this to a .pthml files only for faster processing.

Your IDE should find a match in

https://gist.github.com/marjan7790/d6331447c83d420014d22c4a05a30ca2

The code looks like

https://gist.github.com/marjan7790/b6c7b2fcb8bfadfd3121ac77a6899acf

Yes, the $block has a method that creates a checkout object, which among other properties, has the maxItemsToDisplay set as well.

By the way, if you were to debug, eventually you will figure the maxItemsToDisplay gets to be populated from the configuration value from

Configuration -> Sales -> Checkout (Common sense, remember?) -> Shopping cart Sidebar -> Maximum number of items to display

But regardless of that, you should by now have an idea how to edit this if needed. There can be many ways like:

  • override the block by adding new method like getMySerializedConfig() and call that method in an overridden minicart.phtml file
  • override the minicart.phtml by adding a new like

https://gist.github.com/marjan7790/004041751ed52cd46cf449899d1b31f5

There are various possibilities, it really depends on the needs, but, eventually, we will need to focus on passing values directly to the <script type=”text/x-magento-init”>, or in particular, extending this code:

https://gist.github.com/marjan7790/eadbdbe6a8e23dd7b95eea7de1fa80ff

The next article tries to pass our own server data to the Minicart.

Leave a comment