Skip to content

The window.hyva object

When a Hyvä theme is active, a window.hyva JavaScript object is available on every page with some very handy helper functions.

In case you want to look them up, the functions are mostly defined in vendor/hyva-themes/magento2-theme-module/src/view/frontend/templates/page/js/hyva.phtml.

hyva.getCookie(name)

As the name implies, getCookie() is a convenient way to get a given cookie value.

hyva.setCookie(name, value, days, skipSetDomain)

The first two arguments of the setCookie method are required. The third and fourth arguments days and skipSetDomain are optional.

SkipSetDomain will, as the name suggests, skip setting the domain on the cookie. Magento is inconsistent in it’s backend behavior, not always setting the domain on the cookie.

For example, in Magento\Theme\Controller\Result\MessagePlugin::setCookie, the domain is not set for the cookie mage-messages.

As a result, you end up with two cookies, if you were to set mage-messages without setting skipSetDomain to true.

hyva.getBrowserStorage()

The getBrowserStorage method returns either the native localStorage, if it is available, or tries to fall back to the sessionStorage object.

If neither is available (most notably with IOS Safari in private mode), a warning is logged to the console and false is returned.

Example usage:

const browserStorage = hyva.getBrowserStorage();
if (browserStorage) {
    const private_content_expire_key = 'mage-cache-timeout';
    const cacheTimeout = browserStorage.getItem(private_content_expire_key);
    browserStorage.removeItem(private_content_expire_key);
    browserStorage.addItem(private_content_expire_key, 3600);
}

hyva.postForm(postParams)

The postForm method first creates a new <form> element, then adds hidden fields for a given data object, and finally submits the created form. It automatically adds the uenc and the form_key parameters (uenc is often used by Magento to redirect the visitor back to the page).

The argument postParams is an object with form configuration:

{
    action: "the form action url to post to",
    data: {
        field_a: "value A",
        field_b: "value B"
    }
}

Example: post form data by clicking a link (using Alpine.js)

<a href="#" @click.prevent="hyva.postForm({
  action: 'https://example.test/custom_quote/move/inQuote/',
  data: { id: '<?= $escaper->escapeJs($block->getQuoteId()) ?>' }
})">Request a Quote</a>

hyva.getFormKey()

The getFormKey method returns the current form key value. It is fetched directly from the form_key cookie, or generated when that cookie does not exist.

hyva.formatPrice(value, showSign)

The formatPrice method formats and returns the given value using the current currency. The showSign argument is optional. If it is set to true, a + or - symbol is always rendered.

Otherwise, by default only - is rendered for negative values.

hyva.str(string, ...args)

Available since Hyvä 1.1.17

The str function replaces positional parameters like %1 with the additional argument in the matching position.
The first additional argument replaces %1, the second %2, and so on.

Example:

hyva.str('%2 %1 %3', 'a', 'b', 'c') // => "b a c"
To insert a literal % symbol followed by a number duplicate the %.
For example %%2 is returned as %2.

The behavior of hyva.str is similar to the Magento PHP function __() in regard to the positional parameters.
This allows using some translation phrases with positional parameters in PHP and in JavaScript.

// JavaScript
hyva.str('Welcome %1', customer.firstName);
// PHP
__('Welcome %1', $customer->getFirstname())

hyva.strf(string, ...args)

Available since Hyvä 1.1.14

The strf function replaces positional parameters like %0 in the first argument with additional arguments in the matching position.
The first additional argument replaces %0, the second %1, and so on.

Example:

hyva.strf('%1 %0 %2', 'a', 'b', 'c') // => "b a c"
To insert a literal % symbol followed by a number duplicate the %.
For example %%2 is returned as %2.

hyva.str vs hyva.strf

hyva.strf is almost identical to hyva.str, except that for hyva.strf the first additional argument replaces %0, while for hyva.str it replaces %1.

In general, using hyva.str is preferable, because it behaves similar to the Magento PHP function __(), which also uses %1 to refer to the first additional argument.
This means existing translation phrases which are also used with the PHP function __() may be reused with hyva.str.

hyva.replaceDomElement(targetSelector, content)

Available since Hyvä 1.1.14

The replaceDomElement method replaces the DOM element specified by targetSelector with the innerHTML of the same selector from the string content.

This is useful to replace a part of the page with the same part from a HTML response to an Ajax request.
The function extracts <script> tags from the returned content and adds them to the page head to ensure they are executed.

Example:

window.fetch(url, {
  method: 'POST',
  body: payload
})
.then(result => result.text())
.then(body => {
  hyva.replaceDomElement('#maincontent', body)
})
.catch(error => {
  console.error(error);
  window.location.reload()
})

hyva.getUenc()

Available since Hyvä 1.1.17

The getUenc method is intended to be used to supply the value for the uenc query arguments that is commonly used in Magento.
It allows Magento to redirect the visitor back to the previous page.

"body": "form_key=" + hyva.getFormKey() + "&uenc=" + hyva.getUenc(),

The method returns a properly encoded version of window.location.href.
Besides base64 encoding the current URL, it also takes care of the special characters +. / and = in a way compatible with \Magento\Framework\Url\Encoder::encode().