4

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?

1
  • Sorry guys. This is a Magento 2 question specifically. Also, I just realised my assumption was wrong, and this variable is only available on the /checkout/cart/ page. Commented Apr 8, 2016 at 0:42

1 Answer 1

9

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>
1
  • it is coming up as blank for guest user, Commented Dec 5, 2018 at 6:36

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.