0
我有一個表'內容',您可以爲您的內容分配類別。Ajax搜索過濾器
class Content
{
private $name;
private $categories;
...
...
...
public function __construct()
{
$this->categories = new \Doctrine\Common\Collections\ArrayCollection();
}
public function addCategories(\Publicartel\AppBundle\Entity\Category $categories)
{
$this->categories[] = $categories;
return $this;
}
public function removeCategories(\Publicartel\AppBundle\Entity\Category $categories)
{
$this->categories->removeElement($categories);
}
public function setCategories(\Publicartel\AppBundle\Entity\Category $categories = null)
{
$this->categories = $categories;
return $this;
}
public function getCategories()
{
return $this->categories;
}
}
然後我做了一個查詢來查找所有類別並將它們顯示在頁面上。
$categories = $em->getRepository('PublicartelAppBundle:Category')->getAllCategories();
public function getAllCategories()
{
$em = $this->getEntityManager();
$dql = 'SELECT c FROM Publicartel\AppBundle\Entity\Category c';
$query = $this->getEntityManager()
->createQuery($dql)
->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);
return $query->execute();
}
顯示模板樹枝中的所有分類。
<div class="form-group">
<label for="publicartel_appbundle_category_name">Buscar por categoría:</label>
<select id='selectCategory' class="form-control select2">
{% for categories in categories %}
<option>
{{ categories.name }}
</option>
{% endfor %}
</select>
</div>
我分配了一個句柄來選擇顯示類別,從ajax中傳遞select中的值。
我有一個功能來檢測選擇選項中的變化。
保存選擇值傳遞給所述控制器來執行查詢:
$('#selectCategory').change(function() {
var optionSelect = $(this).val();
console.log(optionSelect);
$.ajax({
url: '{{path('playlist_new') }}',
data: '&category='+optionSelect,
type: 'POST',
success: function(catContent) {
{% for contentCategory in catContent %}
var nameContent = '{{ contentCategory.name }}';
console.log(nameContent);
{% endfor %}
$('playlist_content_name').html(nameContent);
},
error: function(e){
console.log(e.responseText);
}
});
});
$category = $request->query->get('category');
$catContent = $em->getRepository('PublicartelAppBundle:Content')->findByCategory($category);
return $this->render('PublicartelAppBundle:Playlist:new.html.twig', array(
'catContent' => $catContent,
'categories' => $categories,
'entity' => $entity,
'form' => $form->createView(),
));
顯示從所選類別中的內容的查詢:
public function findByCategory($category)
{
$em = $this->getEntityManager();
$dql = 'SELECT c FROM Publicartel\AppBundle\Entity\Content c';
if (!is_null($category)) {
$dql .= " WHERE c.categories.name LIKE :category";
}
$query = $this->getEntityManager()
->createQuery($dql)
->setHydrationMode(\Doctrine\ORM\Query::HYDRATE_ARRAY);
if (!is_null($category)) {
$query->setParameter('category', '%'.$category.'%');
}
return $query->getResult();
}
但是控制檯總是示出了相同的結果,但在我的選擇中選擇不同的選項。
是選擇您選擇的選項,始終顯示相同的結果。