2011-04-06 136 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