开发者

Symfony: how to implement a search functionality on multiple modules?

开发者 https://www.devze.com 2022-12-17 19:39 出处:网络
I have for example a mod开发者_如何转开发ule in my applications called \'Books\'. Also I have several others modules in which I want to use a \'search a book\' functionality (reuse the search form).

I have for example a mod开发者_如何转开发ule in my applications called 'Books'. Also I have several others modules in which I want to use a 'search a book' functionality (reuse the search form).

How can I achieve that?

I tried to make a component for this and use it in other modules templates, but I don't know how to return the found book id from it (I use some ajax, but no luck). Or maybe this is just a wrong approach.

Any suggestions? Thanks.


A component or action will do a perfect job, because they provide the reusability you want !

Here's a very basic approach :

The action is straightforward, take a request parameter and perform a search

/* books actions.class.php */
executeSearch($request){
    // clean search term
    $search = trim($request->getParameter('query'));
    // perform Query (Doctrine ORM)
    $books = Doctrine_Core::getTable("Books")->findByTitle($search);
    // Ajax Request ?
    if ($request->isXmlHttpRequest()){
        return $this->renderPartial('result', array("books" => $books);
    }
    else {
        // HTML Request
        $this->setTemplate("result");
        return sfView::SUCCESS;
    }   
}

Search form

/* books search.php */
<form action="<?php echo url_for('books/search') ?>">
    <input type="text" name="query"></input>
    <input type="submit"></input>
</form>

Result partial

/* books result.php */
<ul>
    <?php foreach($books as $book): ?>
        <li><?php echo $book; ?></li>
    <?php endforeach; ?>
<ul>

So this is quite reusable, you can do a jQuery.load() or whatever you want to "ajax" and on the other hand you can perform an old style HTTP search (progressive enhancement !).

PS: Of course you can perform your search via sfLucense (from jon's post) or another fulltext solutions


You wouldnt use a component really unless you want to render a partial as part of the process. With that said you could simply return the string of the id in that partial view or return a complete json representation or whatever else you need.


Have you looked into the sfLucene plugin?

The plugin allows you to index the models you require and give weighting if you require.

From the search results you can set the route to be show, so your results can point to exactly the page you require.

It is fairly easy to create a partial containing a search form to be added to your layout too, so you can have the search box on any age you wish.

0

精彩评论

暂无评论...
验证码 换一张
取 消