Useful Hyva JavaScript helper functions
Chapters Close

Useful Hyva JavaScript helper functions

In this post, I will explain the most Useful Hyva JavaScript helper functions in Hyva themes.

In hyva theme, window.hyva JavaScript object is available on every page with some Useful helper functions.

You can find these helper functions defined in vendor/hyva-themes/magento2-theme-module/src/view/frontend/templates/page/js/hyva.phtml file.

hyva.getFormKey()

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

When you use <?php echo $block->getBlockHtml(‘formkey’)?> form key is getting cached and sometimes you will get an “invalid form key” error while submitting the form.

You should use the form key in the below way to prevent an invalid form key issue.

<input type="hidden" name="form_key" :value="hyva.getFormKey()" />

hyva.getCookie(name)

hyva.getCookie method is used for getting the cookie value by cookie name. 

This method has one argument. 

  • name:  First argument is the cookie name and it is required. 

You need to pass the cookie name in hyva.getCookie method and it will return the cookie value.

let cookieName = 'my_cookie_name';
hyva.getCookie(cookieName);

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

hyva.setCookie method is used for setting the cookie. 

This method has four arguments:

  • name: First argument is cookie name and it is required. 
  • value: Second argument is cookie value and it is required.
  • days: Third argument is days which is optional, here you need to add the cookie expiry value in days.
  • skipSetDomain: Forth argument is skipSetDomain which is optional, This will skip setting the domain on the cookie. Magento is inconsistent in its backend behavior, not always setting the domain on the cookie. 
let cookieName = 'my_cookie_name';
let cookieValue = 'test';
let cookieExpireDays = 7;
hyva.setCookie(cookieName, cookieValue, cookieExpireDays);

hyva.setSessionCookie(name, value, skipSetDomain)

hyva.setSessionCookie method is identical to hyva.setCookie method with one difference, that the cookie will have no expiry set, so it will be deleted when no more windows or tags with the site are opened in the browser.

This method has three arguments:

  • name: First argument is cookie name and it is required. 
  • value: Second argument is cookie value and it is required.
  • skipSetDomain: Third argument is skipSetDomain which is optional, This will skip setting the domain on the cookie. Magento is inconsistent in its backend behavior, not always setting the domain on the cookie. 
let cookieName = 'my_ses_cookie_name';
let cookieValue = 'test value';
hyva.setSessionCookie(cookieName, cookieValue);

New to Hyvä?? Learn about the Hyvä Theme from basics!

hyva.formatPrice(value, showSign)

The hyva.formatPrice method formats and returns the given value using the current currency

This method has 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.

<script>
let price = 20;
let priceWithCurrency = hyva.formatPrice(price);
console.log(priceWithCurrency); // => $20.00
</script>

Output:

hyva formarPrice

hyva.str(string, …args)

The hyva.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"

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)

The hyva.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.

Note: The 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.

Example:

hyva.strf('%1 %0 %2', 'a', 'b', 'c') // => "b a c"

hyva.replaceDomElement(targetSelector, content)

The hyva.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()

The getUenc method is intended to be used to supply the value for the uenc query arguments that are commonly used in Magento.

It allows Magento to redirect the visitor back to the previous page.

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

hyva.alpineInitialized(callback)

The alpineInitialized method takes a callback argument that is executed after Alpine.js is loaded and initialized, regardless of the Alpine version.

<script>
    const myTestFunction = () => {
        console.log("myTestFunction executed");
    };
    hyva.alpineInitialized(myTestFunction);
</script>

hyva.postForm(postParams)

The hyva.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"
  },
  skipUenc: false,
}

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

<a href="#" x-data="" @click.prevent="hyva.postForm({
  action: BASE_URL+'custom_quote/move/inQuote/',
  data: { id: '3' }
})">
  Request a Quote
</a>

hyva.getBrowserStorage()

The hyva.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:

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.setItem(private_content_expire_key, 3600);
}

More resources on Hyva themes:

Speak your Mind

Post a Comment

Got a question? Have a feedback? Please feel free to leave your ideas, opinions, and questions in the comments section of our post! ❤️

* This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Grow your online business like 4,256 subscribers

    * This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.
    envelope

    Thank You!

    We are reviewing your submission, and will be in touch shortly.