2011-04-06 138 views
3

由于Symfony中典型的indexSuccess动作,我需要在对象列表中放置一个搜索框。目标很简单:根据条件过滤列表。添加搜索框以筛选Symfony中的结果列表?

我一直在阅读Zend Lucene approach in Jobeet tutorial,但它似乎使用大锤打破螺母(至少对我的要求)。

我对自动生成的管理过滤器表单更感兴趣,但我不知道如何在前端实现它。

我可以简单地将搜索框内容传递给动作并构建一个自定义查询,但有没有更好的方法来做到这一点?

编辑

我忘了提,我想有一个通用输入字段,而不是一个输入字段为每个模型属性。

谢谢!

回答

0

我最后使用的Symfony

public function executeIndex { 
    ... 
    // Add a form to filter results 
    $this->form = new MyModuleForm(); 
} 

生成的默认MyModuleForm但仅显示自定义字段做了一个自定义表单:

<div id="search_box"> 
    <input type="text" name="criteria" id="search_box_criteria" value="Search..." /> 
    <?php echo link_to('Search', '@my_module_search?criteria=') ?> 
</div> 

然后,我创建了一个名为@my_module_search链接到index动作路线:

my_module_search: 
    url:   my_module/search/:criteria 
    param:  { module: my_module, action: index } 
    requirements: { criteria: .* } # Terms are optional, show all by default 

用JavaScript(jQuery的在这种情况下)我追加文本链接的href属性输入到标准参数:

$('#search_box a').click(function(){ 
    $(this).attr('href', $(this).attr('href') + $(this).prev().val()); 
}); 

最后,回到executeIndex行动,我发现如果文本被输入并添加自定义过滤器的DoctrineQuery对象:

public function executeIndex { 
    ... 
    // Deal with search criteria 
    if ($text = $request->getParameter('criteria')) { 
     $query = $this->pager->getQuery() 
      ->where("MyTable.name LIKE ?", "%$text%") 
      ->orWhere("MyTable.remarks LIKE ?", "%$text%") 
      ...; 
    } 

    $this->pager->setQuery($query); 

    ... 
    // Add a form to filter results 
    $this->form = new MyModuleForm(); 
} 

其实,代码更复杂,因为我写了一些泛音和一些我在父类中重用以重用代码。但这是我能想到的最好的。

3

我正在使用此解决方案,而不是集成Zend Lucene,我设法使用自动生成的Symonfy的过滤器。这是我做的方式:

//module/actions.class.php 
public function executeIndex(sfWebRequest $request) 
{ 
     //set the form filter 
     $this->searchForm = new EmployeeFormFilter(); 
     //bind it empty to fetch all data 
     $this->searchForm->bind(array()); 
     //fetch all 
     $this->employees = $this->searchForm->getQuery()->execute(); 
     ... 
} 

我做了一个搜索操作其进行搜索

public function executeSearch(sfWebRequest $request) 
{ 
    //create filter 
    $this->searchForm = new EmployeeFormFilter(); 
    //bind parameter 
    $fields = $request->getParameter($this->searchForm->getName()); 
    //bind 
    $this->searchForm->bind($fields); 
    //set paginator 
    $this->employees = $this->searchForm->getQuery()->execute(); 
    ... 
    //template 
    $this->setTemplate("index"); 
} 

重要的是,搜索表单进入mymodule中/搜索行动。

实际上,我还使用sfDoctrinePager作为分页设置,直接为表单生成的查询正确分页。

如果你想更多的字段添加到搜索表单检查this :)

+0

这迫使我使用模型属性进行过滤,即对每个小部件使用不同的输入。我正在考虑在模型列中使用'LIKE'来创建一个唯一的输入字段并构建一个自定义查询。 – elitalon 2011-04-06 13:32:33

+0

这是一个完全不同的答案......你必须迭代每个字段并进行正确的查询。稍后我会检查我是否可以做到。 – Pabloks 2011-04-06 16:30:26

+0

我知道:)谢谢你的努力。我一直在挖掘后端缓存,试图提出一种基于生成类的替代解决方案。如果我找到了某些东西,我会更新我的答案 – elitalon 2011-04-07 08:41:35