1

Ive recently been working on a change for the search bar field. I have decided to add a toggled search bar inside of my navigation bar which is activated through jquery.

My form-mini.phtml is being called inside of topmenu.phtml like below once the search icon is clicked.

<?php include ($block->getTemplateFile('Magento_Search::form.mini.phtml')) ?>

Everything is working the way we would hope except for search terms entered in this field. The issue occurs when the first person who searches a product on the site will have their search cached and the value field will have their search term populated for everyone on the site trying to use the search function.

How would I stop the search from caching without setting cacheable="false" as I do not want to disable cache on every page of the site.

Search: MySQL

Cache: Varnish and Magento Full Page Cache

1 Answer 1

1

You need to add a cache key that is unique per search query.

Create a plugin for the topmenu block in di.xml:

<type name="Magento\Theme\Block\Html\Topmenu">
    <plugin name="topmenu_searchbar" type="Vendor\Package\Plugin\Block\Topmenu" />
</type>

Then use the getAfterCacheKeyInfo() method:

<?php

namespace Vendor\Package\Plugin\Block;

class Topmenu
{
    /**
     * @var \Magento\Search\Helper\Data
     */
    private $searchHelper;

    public function __construct(
        \Magento\Search\Helper\Data $searchHelper
    ) {
        $this->searchHelper = $searchHelper;
    }

    /**
     * Since the search bar was moved into the topnav, we need to add a key for the search term
     * so it doesn't get cached.
     */
     public function afterGetCacheKeyInfo(\Magento\Theme\Block\Html\Topmenu $subject, $result)
     {
         $result[] = $subject->getUrl('*/*/*', ['_current' => true, 'q' => $this->searchHelper->getEscapedQueryText()]);
         return $result;
     }
}
1
  • 1
    It works for me Thank you so much. Do you have another solution ? Commented Sep 21, 2019 at 15:10

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.