Search

Fork has a built-in search system. This allows visitors to easily find items on the website. To use this search function, you have to enable searching for this module - we'll explain this later, have a search function in you frontend model and add indexes when you add or edit your posts.

Indexes

To enable the search engine to find your post, you have to add it. To do this, you need the code below.

use Backend\Modules\Search\Engine\Model as BackendSearchModel;

...

// save searchindex
BackendSearchModel::saveIndex(
	$this->getModule(), $item['id'],
	array(
		'title' => $item['title'],
		'introduction' => $item['introduction'],
		'text' => $item['text']
	)
);

The post will now be added to the search index so we can use this data later on.

Searching

When we search for a term, the search engine will go trough this data and return the ids and modules that match the term.

The next thing it does, is check if there is a callback available to the frontend model of that module. Note, a module search function should always:

  • accept an array of entry id's
  • return only the entries that are allowed to be displayed, with their array's index being the entry's id

The search function for our mini blog module looks like this:

use Frontend\Core\Engine\Model as FrontendModel;
use Frontend\Core\Engine\Navigation as FrontendNavigation;

...

public static function search(array $ids)
{
	$items = (array) FrontendModel::get('database')->getRecords(
		'SELECT i.id, i.title, i.introduction, i.text, m.url
		 FROM mini_blog AS i
		 INNER JOIN meta AS m ON i.meta_id = m.id
		 WHERE i.publish = ? AND i.language = ?',
		array(true, FRONTEND_LANGUAGE), 'id'
	);

	// prepare items for search
	$detailUrl = FrontendNavigation::getUrlForBlock('mini_blog', 'detail');
	foreach($items as $key => $item)
	{
		$items[$key]['full_url'] = $detailUrl . '/' . $item['url'];
	}

	return $items;
}

The advantage of this system is that we can select the posts we want to display in our search engine. Here we filter all the posts that are not visible and that are not in our frontend language.

After that, we assign the full url for each item and return the array of items.

Note that we set our record keys to the id of the item

array(true, FRONTEND_LANGUAGE), 'id'

This way, the search engine will validate if that item is actually in the search engine results for the specific keyword the user is searching for. If not, it will delete that item from the results.