1

I'm working on a module to make certain CMS pages searchable on the front end. Right now I'm having a little trouble filtering the pages. I get the collection, filter it by an "is_searchable" field that I've added, which is working fine. When I try to filter it by title or content using a like statement, it either returns no results, or every result, regardless of if that matches the title/content at all or not. Here's what I'm using so far:

$results = Mage::getModel('cms/page')->getCollection()
               ->addFieldToFilter('title', array('like'=> '%' . $search . '%'))
               ->addFieldToFilter('content', array('like'=>'%' . $search . '%'))
               ->addFieldToFilter('is_searchable', 1);

I also tried using addAttributeToFilter() but get an error that that function doesn't exist in that model. Not sure what I'm doing wrong here, but any help or direction would be appreciated. Thanks!

2 Answers 2

2

The answer by @MauroNigrele comes close, but the actual syntax to combine several conditions for different fields with OR is different.

The following should work:

$results = Mage::getModel('cms/page')->getCollection()
    ->addFieldToFilter(
        ['title', 'content'],
        [['like' => "%{$search}%"], ['like' => "%{$search}%"]]
     )
     ->addFieldToFilter('is_searchable', 1);

You can find a more detailed documentation of addFieldToFilter() in this answer: addFilter vs addFieldToFilter

2

In this query you are looking for pages with both title and content like $search i mean AND not OR.

If you need to build an OR statement the right syntax is:

$results = Mage::getModel('cms/page')->getCollection()
     ->addFieldToFilter(array(
        array('field'=> 'title','like' => "%{$search}%"),
        array('field'=> 'content','like' => "%{$search}%"),
     ))
     ->addFieldToFilter('is_searchable', 1);

You can always view your query logging the select:

Mage::log($results->getSelectSql(true),7,'my-sql.log');

Remember that addAttributeToFilter() method is only available for EAV entities and these are: catalog_product, catalog_category ,customer_customer and customer_address

1
  • Hi, thanks for your answer. Unfortunately this doesn't quite work. When the query gets built, it comes out as SELECT main_table.* FROM cms_page AS main_table WHERE ((title.`` = '') OR (content.`` = '')) AND (is_searchable = '1') and I'm getting the error that the columnt 'title.' doesn't exist. I'm not too familiar with how Magento is actually building the query so I'm not too sure what the correct syntax would be to just have it looking for 'title'
    – Eric Strom
    Commented Jan 22, 2016 at 18:26

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.