我正在实施一个简单的搜索功能,我已经在其他项目上使用而没有任何问题。出于某种原因,它给我的showAction错误 - 显示页面'我无法弄清楚原因。
Impossible to access an attribute ("title") on a NULL variable ("") in AcmeBundle:Blog:show.html.twig at line 9
我在showAction中的$ blog变量上做了转储(这给了我上面的错误 - 如果我没有注释掉if语句我在showAction()中得到了NotFoundException。我的搜索代码没有&甚至可以去任何节目动作或模板。
我的博客实体与一个实体有一个ManyToMany关系,另一个实体有ManyToOne,不确定这是否会弄乱我的搜索代码?
问题:我不知道为什么搜索功能会转到我的showAction以及它为什么会出现空?
的showAction()
/**
* @Route("/{slug}", name="AcmeBundle_show")
* @Method("GET")
* @Template("AcmeBundle:Blog:show.html.twig")
*/
public function showAction($slug)
{
$em = $this->getDoctrine()->getManager();
$blog = $em->getRepository('AcmeBundle:Blog')->findOneBy(array(
'slug' => $slug
));
var_dump($blog);
if (!$blog) {
throw $this->createNotFoundException('Unable to find blog post');
}
return array(
'blog' => $blog,
'slug' => $slug,
);
}
搜索代码作为服务
public function search()
{
$results = null;
$query = $this->request->query->get('q');
if (!empty($query)) {
$em = $this->doctrine->getManager();
$results = $em->createQueryBuilder()
->from('AcmeBundle:Blog', 'b')
->select('b')
->where('b.title LIKE :search')
->addOrderBy('b.created', 'DESC')
->setParameter('search', "%${query}%")
->getQuery()
->getResult();
}
return array(
'query' => $query,
'results' => $results,
);
带有searchAction的控制器
/**
* @Route("/search", name="AcmeBundle_search")
* @Template("AcmeBundle:Page:search.html.twig")
*/
public function searchAction()
{
$em = $this->getDoctrine()->getManager();
// Search code: calling from the service Search
$query = $this->get('search');
$results = $query->search();
$recentBlogLimit = $this->container->getParameter('acme.latest.blogs_limit');
$latestBlogs = $em->getRepository('AcmeBundle:Blog')
->getBlogs($recentBlogLimit);
$tags = $em->getRepository('AcmeBundle:Tag')
->getTags();
return array(
'query' => $query,
'results' => $results['results'],
'latestBlogs' => $latestBlogs,
'tags' => $tags,
);
}
在树枝上搜索代码
<section class="section">
<form action="{{ path('AcmeBundle_search') }}" method="GET">
<label><input type="search" name="q" value={{ app.request.query.get('q') }}></label>
<input type="submit" value="Search">
</form>
</section>