0

I am using Magento 2 with a hyva Theme when I go to the login page and write the wrong credentials it will not give an error Massage like Please provide correct credentials in this page /customer/account/login/ can anyone guide me to do that How to solve I didn't show an error message And redirect to on the same page without any error video link check ==> https://www.awesomescreenshot.com/video/19241045?key=6bbe82d68d414e53d9ae94f677a5f6aa

Here is my login.phtml code

<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */
 
declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\Customer\LoginButton;
use Hyva\Theme\ViewModel\HeroiconsOutline;
use Hyva\Theme\ViewModel\HeroiconsSolid;
use Hyva\Theme\ViewModel\ReCaptcha;
use Magento\Customer\Block\Form\Login;
use Magento\Framework\Escaper;

$heroiconsoutline = $viewModels->require(HeroiconsOutline::class);
$heroiconssolid = $viewModels->require(HeroiconsSolid::class);
$loginButtonViewModel = $viewModels->require(LoginButton::class);

// Do not replace this with $viewModels->require(ReCaptcha::class); that might break the dependency
// on the Magento_ReCaptchaCustomer module
$recaptcha = $block->getData('viewModelRecaptcha');
?>
<div class="w-full md:w-1/2 card mr-4">
    <div aria-labelledby="block-customer-login-heading">
        <form class="form form-login"
              action="<?= $escaper->escapeUrl($block->getPostActionUrl()) ?>"
              method="post"
              x-data="initCustomerLoginForm()"
              @submit.prevent="submitForm()"
              id="customer-login-form">
            <?= $block->getBlockHtml('formkey') ?>
            <fieldset class="fieldset login">
                <legend class="mb-3">
                    <h2 class="text-xl font-medium title-font text-primary">
                        <?= $escaper->escapeHtml(__('Login')) ?>
                    </h2>
                </legend>
                <div class="text-secondary-darker mb-8">
                    <?= $escaper->escapeHtml(
                        __('If you have an account, sign in with your email address.')
                    ) ?>
                </div>
                <div class="field email required">
                    <label class="label" for="email"><span><?= $escaper->escapeHtml(__('Email')) ?></span></label>
                    <div class="control">
                        <input name="login[username]"
                               class="form-input"
                               required
                               value="<?= $escaper->escapeHtmlAttr($block->getUsername()) ?>"
                            <?php if ($block->isAutocompleteDisabled()): ?>
                                autocomplete="off"
                            <?php endif; ?>
                               id="email"
                               type="email"
                               title="<?= $escaper->escapeHtmlAttr(__('Email')) ?>"/>
                               
                    </div>
                </div>
                <div class="field password required">
                    <label for="pass" class="label"><span><?= $escaper->escapeHtml(__('Password')) ?></span></label>
                    <div class="control flex items-center">
                        <input name="login[password]"
                               class="form-input"
                               required
                               :type="showPassword ? 'text' : 'password'"
                            <?php if ($block->isAutocompleteDisabled()): ?>
                                autocomplete="off"
                            <?php endif; ?>
                               id="pass"
                               title="<?= $escaper->escapeHtmlAttr(__('Password')) ?>"/>
                               
                        <div x-on:click="showPassword = !showPassword"
                             class="cursor-pointer px-4"
                             :aria-label="showPassword ? '<?= $escaper->escapeJs(__('Hide Password')) ?>' : '<?= $escaper->escapeJs(__('Show Password')) ?>'"
                        >
                            <template x-if="!showPassword">
                                <?= $heroiconssolid->eyeHtml('w-5 h-5'); ?>
                            </template>
                            <template x-if="showPassword">
                                <?= $heroiconssolid->eyeOffHtml('w-5 h-5'); ?>
                            </template>
                        </div>
                    </div>
                </div>

                <?= $recaptcha ? $recaptcha->getInputHtml(ReCaptcha::RECAPTCHA_FORM_ID_CUSTOMER_LOGIN) : '' ?>
                <?= $block->getChildHtml('form_additional_info') ?>
                <div class="actions-toolbar flex justify-between pt-6 pb-2 items-center">
                        <button type="submit" class="btn btn-primary disabled:opacity-75" name="send"
                            <?php if ($loginButtonViewModel->disabled()): ?> disabled="disabled" data-recaptcha-btn<?php endif; ?>
                        >
                            <span><?= $escaper->escapeHtml(__('Sign In')) ?></span></button>
                        <a class="underline text-secondary" href="<?= $escaper->escapeUrl(
                            $block->getForgotPasswordUrl()
                        ) ?>"><span><?= $escaper->escapeHtml(__('Forgot Your Password?')) ?></span>
                        </a>
                </div>
                <div>
                    <template x-if="displayErrorMessage">
                        <p class="text-red flex items-center">
                            <span class="inline-block w-8 h-8 mr-3">
                                <?= $heroiconsoutline->exclamationCircleHtml(); ?>
                            </span>
                            <template x-for="errorMessage in errorMessages">
                                <span x-html="errorMessage"></span>
                            </template>
                        </p>
                    </template>
                </div>
            </fieldset>
        </form>
    </div>
    <div class="w-full">
        <?= $recaptcha ? $recaptcha->getLegalNoticeHtml(ReCaptcha::RECAPTCHA_FORM_ID_CUSTOMER_LOGIN) : '' ?>
    </div>
    <script>
        function initCustomerLoginForm() {
            return {
                errors: 0,
                hasCaptchaToken: 0,
                showPassword: false,
                displayErrorMessage: false,
                errorMessages: [],
                setErrorMessages(messages) {
                    this.errorMessages = [messages]
                    this.displayErrorMessage = this.errorMessages.length
                },
                submitForm() {
                    // do not rename $form, the variable is the expected name in the recaptcha output
                    const $form = document.querySelector('#customer-login-form');
                    <?= $recaptcha ? $recaptcha->getValidationJsHtml(ReCaptcha::RECAPTCHA_FORM_ID_CUSTOMER_LOGIN) : '' ?>

                    if (this.errors === 0) {
                        $form.submit();
                    }
                }
            }
        }
    </script>
</div>

Here is my message.phtml code

<?php


declare(strict_types=1);

use Hyva\Theme\Model\ViewModelRegistry;
use Hyva\Theme\ViewModel\HeroiconsOutline;

$heroicons = $viewModels->require(HeroiconsOutline::class);

?>
<script>
    function initMessages() {
        "use strict";
        return {
            messages: window.mageMessages || [],
            isEmpty() {
                return this.messages.reduce(
                    function (isEmpty, message) {
                        return isEmpty && message === undefined
                    }, true
                )
            },
            removeMessage(messageIndex) {
                this.messages[messageIndex] = undefined;
            },
            addMessages(messages, hideAfter) {
                messages.map((message) => {
                    this.messages = this.messages.concat(message);
                    if (hideAfter) {
                        this.setHideTimeOut(this.messages.length -1, hideAfter);
                    }
                });
            },
            setHideTimeOut(messageIndex, hideAfter) {
                setTimeout((messageIndex) => {
                    this.removeMessage(messageIndex);
                }, hideAfter, messageIndex);
            },
            eventListeners: {
                ['@messages-loaded.window']() {
                    this.addMessages(event.detail.messages, event.detail.hideAfter)
                },
                ['@private-content-loaded.window'](event) {
                    const data = event.detail.data;
                    if (
                        data.messages &&
                        data.messages.messages &&
                        data.messages.messages.length
                    ) {
                        this.addMessages(data.messages.messages);
                    }
                },
                ['@clear-messages.window']() {
                    this.messages = [];
                }
            }
        }
    }
</script>
<section id="messages"
         x-data="initMessages()"
         x-spread="eventListeners"
>
    <template x-if="!isEmpty()">
        <div class="w-full">
            <div role="alert" class="messages container mx-auto py-3">
                <template x-for="(message, index) in messages" :key="index">
                    <div>
                        <template x-if="message">
                            <div class="message" :class="message.type"
                                 :ui-id="'message-' + message.type"
                            >
                                <span x-html="message.text"></span>
                                <a href="#" class="close cursor-pointer" title="close"
                                   @click.prevent="removeMessage(index)">
                                    <?= $heroicons->xHtml('text-white', 18, 18); ?>
                                </a>
                            </div>
                        </template>
                    </div>
                </template>
            </div>
        </div>
    </template>
</section>

Where we are wrong I don't know can anybody know how to solve this issue?

1
  • Did you update the Hyva version? Which version of Hyva are you currently using?
    – Msquare
    Nov 10, 2023 at 15:12

2 Answers 2

0

If you are using alpinejs version 2, which is the default, then the problem is related to the way hyva.initMessages is triggered in cookies.phtml.

The event alpine:initialized is only available in alpine v3.

Override Hyva_Theme::page/js/cookies.phtml and change
window.addEventListener('alpine:initialized', hyva.initMessages);
to
window.addEventListener('load', hyva.initMessages);

The same eventlistener is used in private-content.phtml
Override Hyva_Theme::page/js/private-content.phtml and change
window.addEventListener('alpine:initialized', loadSectionData);
to
window.addEventListener('load', loadSectionData);

0

We also face the same issue on our hyva theme upgrade.

For Alpine.js version 3, you can update the files from your latest vendor directory.

Massage show Issue:

vendor/hyva-themes/magento2-theme-module/src/view/frontend/templates/page/js/cookies.phtml

Checkout Cart Issue:

vendor/hyva-themes/magento2-theme-module/src/view/frontend/templates/page/js/private-content.phtml

For Alpine.js version 2, I have included the older version here.

app/design/frontend/VendorName/ThemeName/Hyva_Theme/templates/page/js/cookies.phtml

<?php
/**
 * Hyvä Themes - https://hyva.io
 * Copyright © Hyvä Themes 2020-present. All rights reserved.
 * This product is licensed per Magento install
 * See https://hyva.io/license
 */

declare(strict_types=1);

/** @var \Magento\Framework\View\Element\Template $block */
?>
<script>
    'use strict';
    function dispatchMessages(messages, hideAfter) {
        const messagesEvent = new CustomEvent("messages-loaded", {
            detail: {
                messages: messages,
                hideAfter: hideAfter
            }
        });
        window.dispatchEvent(messagesEvent);
    }

<?php
    /**
     * The `hyva` JS namespace is being set by Hyva_Theme/src/view/frontend/templates/page/js/hyva.phtml
     * and should be included through Hyva_Theme/src/view/frontend/layout/default_hyva.xml
     */
?>
    if (typeof hyva === 'undefined' || (!hyva.getBrowserStorage || !hyva.getCookie || !hyva.setCookie)) {
        console.warn("Hyvä helpers are not loaded yet. Make sure they are included before this script");
    }

    (function( hyva, undefined ) {

        hyva.initFormKey = () => {
            const inputSelector = 'input[name="form_key"]',
                formKey = hyva.getFormKey();

            Array.from(document.querySelectorAll(inputSelector)).map(function (input) {
                input.value = formKey
            });
        }

        hyva.initMessages = () => {
            try {
                const messages = hyva.getCookie('mage-messages');
                window.mageMessages = messages ? JSON.parse(decodeURIComponent(messages).replace(/\+/g, ' ')) : [];

                dispatchMessages(window.mageMessages);

                <?php
                /**
                 * In \Magento\Theme\Controller\Result\MessagePlugin::setCookie
                 * the cookie-domain is not set. Therefore, we need to skip it
                 * here as well.
                 */
                ?>
                // empty `mage-messages` cookie
                const skipSetDomain = true;
                hyva.setCookie('mage-messages','', -1, skipSetDomain);

            } catch (error) {
                console.warn('Error parsing Cookie Messages:', error);
            }
        }

        window.addEventListener('DOMContentLoaded', hyva.initFormKey);
        window.addEventListener('load', hyva.initMessages);


    }( window.hyva = window.hyva || {} ));
</script>

app/design/frontend/VendorName/ModuleName/Hyva_Theme/templates/page/js/private-content.phtml

<script>
    'use strict';
    {
        const private_content_key = 'mage-cache-storage';
        const private_content_expire_key = 'mage-cache-timeout';
        const private_content_version_key = 'private_content_version';
        const section_data_ids_key = 'section_data_ids';
        const mage_cache_session_id_key = 'mage-cache-sessid';
        const last_visited_store_key = 'last_visited_store';

        const ttl = 3600;

        if (typeof hyva === 'undefined' || (!hyva.getBrowserStorage || !hyva.getCookie || !hyva.setCookie)) {
            console.warn("Hyvä helpers are not loaded yet. Make sure they are included before this script");
        }

        function loadSectionData () {
            const browserStorage = hyva.getBrowserStorage();
            if (!browserStorage) {
                typeof window.dispatchMessages !== "undefined" && window.dispatchMessages(
                    [{
                        type: "warning",
                        text: "Please enable LocalStorage in your browser."
                    }]
                );
                return;
            }
            try {
                let isInvalid = false;

                if (hyva.getCookie(last_visited_store_key) !== CURRENT_STORE_CODE) {
                    isInvalid = true;
                }
                hyva.setCookie(last_visited_store_key, CURRENT_STORE_CODE, false, false);

                if (!hyva.getCookie(mage_cache_session_id_key)) {
                    isInvalid = true;
                    const skipSetDomain = true;
                    const days = false;
                    hyva.setCookie(mage_cache_session_id_key, true, days, skipSetDomain)
                }

                const cookieVersion = hyva.getCookie(private_content_version_key);
                const storageVersion = browserStorage.getItem(private_content_version_key);

                if (cookieVersion && !storageVersion || cookieVersion !== storageVersion) {
                    isInvalid = true;
                }

                const privateContentExpires = browserStorage.getItem(private_content_expire_key);
                if (privateContentExpires && new Date(privateContentExpires) < new Date()) {
                    browserStorage.removeItem(private_content_key);
                }

                if (isInvalid) {
                    fetchPrivateContent([]);
                } else if (cookieVersion && storageVersion && cookieVersion === storageVersion) {
                    const privateContent = JSON.parse(browserStorage.getItem(private_content_key));
                    if (
                        privateContent &&
                        privateContentExpires &&
                        privateContent.cart &&
                        privateContent.customer
                    ) {
                        dispatchPrivateContent(privateContent);
                    } else {
                        fetchPrivateContent([]);
                    }
                } else {
                    dispatchPrivateContent({});
                }

            } catch (error) {
                console.warn('Error retrieving Private Content:', error);
            }
        }

        window.addEventListener('load', loadSectionData);
        window.addEventListener('reload-customer-section-data', loadSectionData);

        function dispatchPrivateContent(data) {
            const privateContentEvent = new CustomEvent("private-content-loaded", {
                detail: {
                    data: data
                }
            });
            window.dispatchEvent(privateContentEvent);
        }

        function fetchPrivateContent(sections) {
            fetch(`${BASE_URL}customer/section/load/?sections=${encodeURIComponent(sections.join(','))}`, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
                .then(response => response.json())
                .then(
                    data => {
                        if (data) {
                            try {
                                const browserStorage = hyva.getBrowserStorage();

                                // merge new data preserving non-invalidated sections
                                const oldSectionData = JSON.parse(browserStorage.getItem(private_content_key) || '{}');

                                if ((! data.cart || ! data.cart.cartId) && oldSectionData['checkout-data']) {
                                    delete oldSectionData['checkout-data'];
                                }
                                const newSectionData = Object.assign(oldSectionData, data);

                                dispatchPrivateContent(newSectionData);

                                // don't persist messages, they've been dispatched already
                                if (newSectionData.messages && newSectionData.messages.messages ) {
                                    newSectionData.messages.messages = [];
                                }

                                browserStorage.setItem(private_content_key, JSON.stringify(newSectionData));

                                const expiresAt = new Date(Date.now() + (ttl * 1000)).toISOString();
                                browserStorage.setItem(private_content_expire_key, expiresAt);

                                const newCookieVersion = hyva.getCookie(private_content_version_key);
                                browserStorage.setItem(private_content_version_key, newCookieVersion);

                                // We don't need the section_data_ids in Hyvä, but we store them for compatibility
                                // with Luma Fallback. Otherwise, not all sections are loaded in Luma Checkout
                                hyva.setCookie(
                                    section_data_ids_key,
                                    JSON.stringify(
                                        Object.keys(data).reduce((sectionDataIds, sectionKey) => {
                                            sectionDataIds[sectionKey] = data[sectionKey]['data_id'];
                                            return sectionDataIds;
                                        }, {})
                                    ),
                                    false,
                                    true
                                );
                            } catch (error) {
                                console.warn("Couldn't store privateContent", error);
                            }
                        }
                    }
                );
        }
    }
</script>

You can check different below

private-content.phtml -> https://www.diffchecker.com/8PhOKkvb/

cookies.phtml -> https://www.diffchecker.com/xmXy1DDM/

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.