Change Search Query String in Magento 1.8 Backend

magento-1.8PHP

In my magento project, I have a requirement where I need to change the user entered query text to something else based on some calculations.

For example, if the user has entered "ABC" in the Global search text field, then

  • I need to change it to "XYZ" and show the results related to the modified query text i.e "XYZ".
  • and also the popular terms which are being generated based on the query text should not get modified by the new query text.

User entered text      product collection results      Popular terms/suggestions
=================      ==========================      =========================
ABC                    XYZ                             ABC

I tried to achieve the above by doing many things but didn't get success. One of my attempts is overriding prepare() function in Mage_Catalogsearch_Model_Query Class.

public function prepare()
{
    Mage::log("I am in overriden prepare function");
    if($this->getQueryText() == "ABC"){
        $this->setQueryText("XYZ");
    }
    Mage::log($this->getQueryText());
    if (!$this->getId()) {
        $this->setIsActive(0);
        $this->setIsProcessed(0);
        $this->save();
        $this->setIsActive(1);
    }
    return $this;
}

In the above function, though I am able to change the query text by using setQueryText, I am getting the result product collection based on the user entered query text instead of modified query text.

PS: the above function is just an example of how I am trying to achieve it.

EDIT:

I actually need to do some calculations based on the passed query string. To be precise, I need to look for a colon : in the query string and if there is colon then split the string. After splitting, pass the second part of the string as query string, if and only if the first part of the string is a "category name" or "show" or "some other valid strings choosed by me".

Best Answer

I have solved it!!

but I am not sure whether this is the best approach.

The string manipulation operations can be done at prepareResult function of Mage_CatalogSearch_Model_Resource_Fulltext.

public function prepareResult($object, $queryText, $query)
{
    $adapter = $this->_getWriteAdapter();
    if (!$query->getIsProcessed()) {
        //other code....
    }
}

In the above code, I just called my string manipulation function at function's start and also I commented the if statement i.e if(!$query->getIsProcessed()){ because I had many search terms which were already processed. (old database). So, the modified code is:

public function prepareResult($object, $queryText, $query)
{
    $queryText = $this->doStringManipulations($queryText);
    $adapter = $this->_getWriteAdapter();
    //if (!$query->getIsProcessed()) {
        //other code....
    //}
}
Related Topic