2017-01-01 26 views
-1

我想實現一個搜索功能,允許用戶搜索特定實體內的項目,但林不知道,應該怎樣處理這個,基本上,我現在在我的樹枝文件:Symfony的搜索功能

<form id="form_search" action="{{ path('search') }}"> 
    <input type="text" class="form-control" placeholder="Search" name ="find"> 
    <button type="submit" class="btn btn-default"></button> 
</form> 

然後我的控制器中我有:

public function indexAction(Request $request) 
{ 
    if($request->isMethod('GET')) 
    { 
     echo 'get'; 
    } 
    else 
    { 
     echo 'post'; 
    } 

    return $this->render('Bundle:Search:index.html.twig', array(

    )); 
} 

我想從參數得到搜索輸入字段輸入。然而,他們沒有辦法分開用戶是剛剛加載頁面還是實際提交了表單..如你所見,我嘗試瞭解如何通過分離的方式來實現這個想法:

因此,如果用戶加載它不會做搜索的頁面。但是如果用戶提交表單,然後它會執行搜索,但由於某種原因,甚至當我提交打印表單「得到」,而不是「後」

這是爲什麼?

+0

嘗試在你的控制器'$請求 - > getMethod()'呼應這並添加'方法=「郵報」'你的表單標籤 –

回答

0

你需要在你的控制器來定義一個新的功能,您將使用,讓你的搜索,這就是:

class YourController extends Controller 
{ 
    /** 
    * @Route("/", name="index") 
    */ 
    public function indexAction(Request $request) 
    { 

    return $this->render('Bundle:Search:index.html.twig', array()); 
    } 
    /** 
    * @Route("/", name="search") 
    */ 
    public function searchAction(Request $request) 
    { 
     $your_value = $request->get("find"); 
     //implement your search here, 
     $repository = $this->getDoctrine()->getRepository('AppBundle:YourEntity'); 
     $result = $repository->findBy(array("field_name"=>$your_value)); 
     //Here you can return your data in JSON format or in a twig template 
    } 
} 

不要忘記定義實體類,我建議你去看看在此

http://symfony.com/doc/current/doctrine.html

+0

他不是被迫使用不同的功能管理後 –

+0

這是正確的:) – GleyderCova

+0

好,你說:「你需要定義」 :) –