Magento – window.checkoutConfig Javascript (usage)

javascriptmagento2module

It seems that Magento 2, with the default theme, has a JS object window.checkoutConfig which has all the cart information, and is updated when you change the cart.

Is it safe to assume this will be available on all (or most) stores?

If it is not available on a specific store, is there a simple way to get this data otherwise?

Best Answer

Usually the best place to start looking is at the place where it's used. In this case, the onepage checkout.

If you look at public/vendor/magento/module-checkout/view/frontend/templates/onepage.phtml you'll note the following line:

window.checkoutConfig = <?php /* @escapeNotVerified */ echo \Zend_Json::encode($block->getCheckoutConfig()); ?>;

Ergo, if you want to have this configuration anywhere else you need to include this in your template as well. If you take a look at the getCheckoutConfig()-method of Block/Onepage.php you'll see:

/**
 * Retrieve checkout configuration
 *
 * @return array
 * @codeCoverageIgnore
 */
public function getCheckoutConfig()
{
    return $this->configProvider->getConfig();
}

On it's turn $this->configProvider maps to Magento\Checkout\Model\CompositeConfigProvider. Now, if you just re-use this model in your own block class using dependency injection you can simply mimic the same code in your own class:

/**
 * @var \Magento\Checkout\Model\CompositeConfigProvider
 */
protected $configProvider;

/**
 * Constructor call.
 * @param Template\Context $context
 * @param \Magento\Checkout\Model\CompositeConfigProvider $configProvider
 * @param array $data
 */
public function __construct(
    Template\Context $context,
    \Magento\Checkout\Model\CompositeConfigProvider $configProvider,
    array $data = []
)
{
    $this->configProvider = $configProvider;
    parent::__construct($context, $data);
}

/**
 * Retrieve checkout configuration
 *
 * @return array
 */
public function getCheckoutConfig()
{
    return $this->configProvider->getConfig();
}

Now you can use getCheckoutConfig() in your own template/block as well:

<script type="text/javascript">
    window.checkoutConfig = <?php echo \Zend_Json::encode($block->getCheckoutConfig()); ?>;
</script>