I was looking for a decent search feature to add to my blog, and after some reading around, I found this feature very easy and interesting. I found a how to in the bakery, but as several users pointed out, it lacked simplicity and a reindex feature. I kept it to the basics and hope this will work as easy for you as it did for me.
Table of Contents
- Step 1: Download Searchable Behaviour
- Step 2: Create Table For Indexes
- Step 3: Add SearchIndex Model
- Step 4: Update Your Post Model
- Step 5: Add Actions In Your Post Controller
- Step 6: Add Search Input Field
- Step 7: Add search.ctp
- Step 8: Update Routes
- Step 9: Reindex Your Data
- Step 10: Add functions to your post model
- Step 11: Add function to Post Controller
Step 1: Download Searchable Behaviour
Download the latest Searchable Behaviour from here and upload the contents to your app/models directory.
Step 2: Create Table For Indexes
Notice that We've added UNIQUE to the key 'association_key'.
Step 3: Add SearchIndex Model
Step 4: Update Your Post Model
We want to make the model Searchable and to have a minimal of validation of the fields.
Step 5: Add Actions In Your Post Controller
Step 6: Add Search Input Field
Just add this wherever you want your users to search from.
Step 7: Add search.ctp
Here you can see that I've added some nice higlightning and excerpts to the results.
Step 8: Update Routes
As a precautin, add this to routes just to safeguard that the link works.
Step 9: Reindex Your Data
Per default, the new search feature you just added will not index old data. It will only index new data you add from now on. To reindex your old data, follow these steps:
Step 10: Add functions to your post model
Add these functions into your Post Model. Remember, you can change the field you want index.
Step 11: Add function to Post Controller
Add this to your Post Controller:
And presto! You have a fully functional search function with all your data indexed! Just remember to hide or comment out the reindex functionality after you've finished with it.