In this blog post, we have listed the most useful Hyvä JavaScript helper functions, which are accessible via the global window.hyva object on every storefront page. These functions simplify coding and reduce the chances of frontend errors.
Quick Look
| Helper Function Name | Main Use |
|---|---|
hyva.getFormKey() | Retrieves the current Magento form key for secure form submissions. |
hyva.getCookie() | Safely retrieves the value of a specific cookie. |
hyva.setCookie() | Sets a cookie with specified name, value, and options. |
hyva.formatPrice() | Formats a numerical value as a currency string based on store settings. |
hyva.replaceDomElement() | Replaces an existing DOM element with new HTML content. |
hyva.str() / hyva.strf() | Replaces placeholders in strings; useful for translations and dynamic text. |
x-magento-init (Alpine.js) | Initializes Alpine.js components with Magento’s JSON config. |
hyva.formValidation (Alpine.js) | Client-side form validation component. |
window.dispatchMessages() | Displays Magento-style success, error, or info messages to the user. |
BASE_URL, CURRENT_STORE_CODE | Global variables for constructing dynamic URLs. |
These helpers are not put in a dedicated .js file but are dynamically exposed to the global window object by the hyva.phtml template.
Breakdown of the Hyvä JavaScript Helper Functions
1. HyvaJsPriceUtils
It adds a formatPrice() method that takes numbers and adds them in a proper format as per the store’s settings (e.g., currency symbol, decimal places, thousands separator).
// A simple way to format a price
console.log(HyvaJsPriceUtils.formatPrice(10.50));
// Passing additional options (optional)
let formattedPrice = HyvaJsPriceUtils.formatPrice(200.00, {
// Optionally override default formatting options
});
console.log(formattedPrice);
2. hyva.getFormKey()
This function is used for AJAX-based forms where you need to pass the form key along with your request data.
// Retrieve the form key
const form_key = hyva.getFormKey();
// Log it to the console
console.log(form_key);
// You can now include this in your AJAX request payload
// For example: { form_key: form_key, sku: 'my-product-sku' }
3. hyva.getCookie()
The hyva.getCookie(name) retrieves the value of any cookie by its name. It provides a clean and reliable way to access client-side data.
// Retrieve a cookie by name
const myCookieValue = hyva.getCookie('mage-cache-sessid');
// Log the value
console.log(myCookieValue);
4. hyva.replaceDomElement()
The function correctly re-initializes any Alpine.js components within the new HTML, ensuring everything remains interactive.
// Select the element with ID 'cart-count' and replace its content
const newHtml = `
<div x-text="itemCount"></div>
`;
hyva.replaceDomElement('#cart-count', newHtml);
5. window.dispatchMessages()
This function allows you to display system messages (e.g., success, error, warning) to the user via JavaScript.
// Dispatch a single success message
window.dispatchMessages([
{ type: 'success', text: 'Product successfully added to your cart!' }
]);
// Dispatch multiple messages (e.g., an error and a warning)
window.dispatchMessages([
{ type: 'error', text: 'An error occurred during the process.' },
{ type: 'warning', text: 'Some items are low in stock.' }
]);
6. hyva.setCookie()
This function allows you to easily set a cookie’s value, expiration, path, and other options.
// Set a simple cookie
hyva.setCookie('my-app-state', 'active');
// Set a cookie with a 7-day expiration (in milliseconds)
const oneWeekInMilliseconds = 7 * 24 * 60 * 60 * 1000;
hyva.setCookie('user_preference', 'light-mode', { expires: oneWeekInMilliseconds });
// Set a cookie with a specific path
hyva.setCookie('session_data', '12345', { path: '/' });
7. hyva.strf() (String Formatting for Translations)
This function is primarily used for formatting strings that contain placeholders, making it perfect for dynamic text and translations.
// Example of a formatted string from the backend const translatedString = "There are %s items in your cart."; // Use hyva.strf() to replace the placeholder const formattedMessage = hyva.strf(translatedString, 5); console.log(formattedMessage); // Output: "There are 5 items in your cart." // You can also use it with multiple placeholders const multiplePlaceholders = "%s added %s to cart."; const multipleFormatted = hyva.strf(multiplePlaceholders, 'John', 'Product A'); console.log(multipleFormatted); // Output: "John added Product A to cart."
8. hyva.formValidation (Alpine.js)
Hyvä includes a reusable Alpine.js component for client-side form validation. By adding the x-data="hyva.formValidation" attribute to a form, you can leverage standard HTML5 required attributes and other custom validation rules to provide real-time feedback to the user, preventing unnecessary server-side requests.
<form x-data="hyva.formValidation" @submit.prevent="validate">
<div class="field mb-4">
<label for="name" class="block text-gray-400 mb-1">Your Name</label>
<input type="text" id="name" required class="w-full px-3 py-2 rounded-md bg-gray-700 border border-gray-600">
<span class="validation-error text-sm text-red-400 mt-1"></span>
</div>
<div class="field mb-4">
<label for="email" class="block text-gray-400 mb-1">Email</label>
<input type="email" id="email" required class="w-full px-3 py-2 rounded-md bg-gray-700 border border-gray-600">
<span class="validation-error text-sm text-red-400 mt-1"></span>
</div>
<button type="submit" class="w-full bg-blue-600 text-white font-bold py-2 px-4 rounded-md hover:bg-blue-700 transition-colors duration-200">Submit</button>
</form>
9. BASE_URL, CURRENT_STORE_CODE (Global Variables)
For JavaScript code that needs to make API calls or reference dynamic URLs, the global BASE_URL and CURRENT_STORE_CODE variables are invaluable. They are automatically injected by Hyvä’s layout and provide reliable, consistent values for constructing paths regardless of the store’s configuration or base URL.
// Get the current store's URL
console.log(BASE_URL); // e.g., "[https://www.yourstore.com/](https://www.yourstore.com/)"
// Get the store code
console.log(CURRENT_STORE_CODE); // e.g., "en_us"
// Construct a dynamic URL for an API call
const myApiUrl = `${BASE_URL}rest/${CURRENT_STORE_CODE}/V1/custom-endpoint`;
console.log(myApiUrl); // e.g., "[https://www.yourstore.com/rest/en_us/V1/custom-endpoint](https://www.yourstore.com/rest/en_us/V1/custom-endpoint)"
Conclusion
The Hyvä JavaScript helper functions and integrated Alpine.js components are powerful assets for any Magento 2 developer working with the Hyvä theme. By understanding and utilizing these tools, you can write more efficient, cleaner, and more robust frontend code. They abstract away much of the complexity of interacting with Magento’s frontend, allowing you to focus on building great user experiences with confidence.
Embrace these helpers in your next Hyvä project and experience the difference they make!