I am using a simple search function, however the problem is that I am hardcoding the category title value in the controller by a findByTitle then passing that into the search function.
Category has a OneToMany/ManyToOne relationship with Post entity.
Have tried the following but got the following error: Error: Call to a member function getTitle() on a non-object
$em = $this->getDoctrine()->getManager();
$query = $this->get('search');
$category = $em->getRepository('AcmeDemoBundle:Category')
->findAll();
$categoryTitle = $em->getRepository('AcmeDemoBundle:Category')
->findByTitle($category->getTitle());
$posts = $query->search($categoryTitle);
How can I dynamically set this value so I don't have to manually pass this in?
Controller
/**
* Search action
*
* @return array
*
* @Route("/search", name="job1_search")
* @Template("AcmeDemoBundle:Job1:search.html.twig")
*/
public function searchAction()
{
// Search code: calling from the service Search
$em = $this->getDoctrine()->getManager();
$query = $this->get('search');
$categoryTitle = $em->getRepository('AcmeDemoBundle:Category')
->findByTitle('job1');
$posts = $query->search($categoryTitle);
return array(
'query' => $query,
'posts' => $posts['results'],
);
}
Search service
public function search($categoryTitle)
{
$results = null;
$query = $this->request->query->get('q');
if (!empty($query)) {
$em = $this->doctrine->getManager();
$results = $em->createQueryBuilder()
->from('AcmeDemoBundle:Post', 'post')
->select('post')
->where('post.category = :category')
->setParameter('category', $categoryTitle)
->andWhere('post.title LIKE :search')
->addOrderBy('post.created', 'DESC')
->setParameter('search', "%${query}%")
->getQuery()
->getResult();
}
return array(
'query' => $query,
'results' => $results,
);
}
The
findAll()method sends back an array no matter if you have one or multiple entities persistedIt means that on the following lines
You'd have to change
$category->getTitle()which is throwing an error because you are calling the method on the array itself not the entities it contains.It's hard to give more details without knowing exactly what you are trying to do (use one category or multiple, how is it chosen, ect...)