Reputation: 2231
I'm really new to Symfony and am working on an app on 1.4. I could use some input on some logic I'm working on and hope someone here could point me in the right direction.
Currently, I'm working on a simple search module (not one for jobeet or using zend search) that queries multiple tables with some text that the user puts in. The text entered by the user could be found in one or more of three tables: Items, Quests, Npc. All of the found results will display on the search action of the search module.
What I'd like, is that the results show on the search action as links to the proper module (Item, Quests, Npc respectively), but ONLY if there are results of that type found. Example( if quest and item match are found, but not NPC):
Your search found 1 Item:
Item 1
Your search found 1 quest:
Quest 1
Since there were no NPCs found, there was no need to even tell the user there weren't any, so it is omitted. Here's where I run into trouble. I'm not really sure HOW to go about doing this. I could just cop-out and use if statements in the searchSuccess.php and only show those if the count() of the arrays were greater than 1, but that sort of defeats the purpose of mvc, right? Is this the only logical solution to making this happen, or is there another way I'm not seeing?
I'd really appreciate any and all feedback.
Upvotes: 0
Views: 708
Reputation: 60413
There are a myriad of ways to do this the simplest is probably something like so:
// controller
public function executeSearch(sfWebRequest $request)
{
$this->results = array();
// well assume you are using sfForm and have validated the search query
// which is $searchTerm and that each of your tables has a search method
// well also assume youre using object routes for these models
$this->actionMap = array(
'Npc' => 'npc_show',
'Quest' => 'quest_show',
'Item' => 'item_show'
);
foreach(array_keys($this->actionMap) as $model)
{
$modelResults = Doctrine_Core::getTable($model)->search($searchTerm);
if($modelResults)
{
$this->results[$model] = $modelResults;
}
}
return sfView::SUCCESS;
}
So what we have coming to the view is $results
an multidimensional array consisting of top level elements for the models where the query returned results. Models who didnt have any matching results are omitted. $actionMap
holds an array of ModelName => Routename
mappings.
// in your searchSuccess
<?php if(count($results)): ?>
<?php foreach($results as $model => $modelResults): ?>
<?php printf("<h3>Your search found %s %s results:</h3>", $modelResults->count(), $model); ?>
<ul>
<?php foreach($modelResults as $result): ?>
<li><?php echo link_to($result, $actionMap[$model], $result); ?></li>
<?php endforeach; ?>
</ul>
<?php endforeach; ?>
<?php else: ?>
<h3>No results found.</h3>
<?php endif; ?>
Upvotes: 1