First , sorry for my english... So i want to make a request to show my article by category. But each time i just get my own error. So my controller is :
public function categorieAction($slug,$page)
{
if ($page < 1) {
throw new NotFoundHttpException('Page "'.$page.'" inexistante.');
}
$nbPerPage = 5;
$listArticles = $this->getDoctrine()
->getManager()
->getRepository('OAHNewsBundle:Article')
->getAvecCategories($slug, $page, $nbPerPage)
;
$nbPages = ceil(count($listArticles)/$nbPerPage);
if ($page > $nbPages) {
throw $this->createNotFoundException("La page ".$page." n'existe pas.");
}
return $this->render('OAHNewsBundle:News:categorie.html.twig',array(
'listArticles' => $listArticles,
'nbPages' => $nbPages,
'page' => $page
));
}
My repository :
public function getAvecCategories ($page ,$slug, $nbPerPage )
{
$query = $this -> createQueryBuilder ('a')
->leftjoin ( 'a.categories' , 'c' )
->addselect('c')
->where('c.slug = :slug')
->setParameter('slug', $slug)
->leftjoin('a.image', 'i')
->addselect('i')
->orderBy('a.date', 'DESC')
->getQuery()
;
$query
->setFirstResult(($page-1) * $nbPerPage)
->setMaxResults($nbPerPage)
;
return new Paginator($query, true);
}
}
My route :
OAHNews_categorie:
path: /categorie/{slug}/{page}
defaults: { _controller: OAHNewsBundle:News:categorie , page: 1 }
requirements:
page: \d*
And the error i get :
if ($page > $nbPages) {
throw $this->createNotFoundException("La page ".$page." n'existe pas.");
}
The view :
{% extends "OAHNewsBundle::OAH_layout.html.twig" %}
{% block title %} {{ parent() }} - Index{% endblock %}
{% block body_news %}
{% for article in listArticles %}
<div class="article_des_news">
<div class="row">
<div class="col-sm-3">
<a href="{{path('OAHNews_voir', {'slugarticle':article.slugarticle})}}"><img src='{{ asset(article.image.webPath) }}' alt="{{ article.image.alt}}"/></a>
</div>
<div class="col-sm-9">
<a class="titre_article" href="{{path('OAHNews_voir', {'slugarticle':article.slugarticle})}}">{{article.titre}}
</a>
<p><i class="glyphicon glyphicon-pencil"></i> par {{article.auteur}},
<i class="glyphicon glyphicon-time"> </i> {{article.date|date('d/m/y')}}
{% if not article.categories.empty %}
<i class="glyphicon glyphicon-tag"> </i>
{% for categorie in article.categories %}
{{ categorie.nom }}{% if not loop.last %}, {% endif %}
{% endfor %}
{% endif %}
</p>
{{ article.contenu|truncate(100, false, "...")}}
</div>
</div>
</div>
{% endfor %}
<ul class="pagination pull-right">
{# On utilise la fonction range(a, b) qui crée un tableau de valeurs entre a et b #}
{% for p in range(1, nbPages) %}
<li{% if p == page %} class="active"{% endif %}>
<a href="{{ path('OAHNews_accueil', {'page': p}) }}">{{ p }}</a>
</li>
{% endfor %}
</ul>
{% endblock %}
and the link i use :
<ul class="nav nav-pills nav-stacked">
{% for categorie in listCategories %}
<li class='menu'>
<a class="titre_article normalLink" href="{{ path('OAHNews_categorie', {'slug': categorie.slug}) }}">
{{ categorie.nom }}
</a>
</li>
{% endfor %}
</ul>
So what's wrong with my request? Thank you !
Ok I got it ! You're using a Paginator object. This object doesn't give you the results at all. If you want to get the number of articles
, you have to do :
$listArticles->count()
According with the doc of the class
But care, cause you've a little problem of logic on your 'existing page check' : Your Repository can only return to you a maximum of 5 results, so if you try to access the second page, you'll have something like that :
$nbPages = ceil($listArticles->count()/$nbPerPage); // [0 - 5] / 5 = 0 or 1
if ($page > $nbPages) { // if (2 > 0 or 1)
throw $this->createNotFoundException("La page ".$page." n'existe pas.");
}
If you want to check if you're accessing an existing page, you just can do :
if ($listArticles->count() > 0) {
throw $this->createNotFoundException("La page ".$page." n'existe pas.");
}
And in your return you must send the array of results to your template by doing :
return $this->render('OAHNewsBundle:News:categorie.html.twig',array(
'listArticles' => $listArticles->getIterator(),
'nbPages' => $nbPages,
'page' => $page
));
Problem 2 : You have the error of the offset equal -5 because of this line of your repo :
->setFirstResult(($page-1) * $nbPerPage) // $page = 0 so (0-1) * 5 = -5
And this is because you defined you getAvecCategories
like that :
getAvecCategories ($page ,$slug, $nbPerPage ) // page, slug, nbPerPage
And you're calling it by inversing arguments :
->getAvecCategories($slug, $page, $nbPerPage) // slug, page, nbPerPage
So php try to cast a slug in int and return 0.
The route should be
OAHNews_categorie:
path: /categorie/{slug}/{page}
defaults: { _controller: OAHNewsBundle:News:categorie , page: 1 }
requirements:
page: \d+ <-- change \d* by \d+
Try to cast the variable before check :
if (intval($page) > $nbPages) {
throw $this->createNotFoundException("La page ".$page." n'existe pas.");
}
Else, dump($page)
and dump($nbPages)
to know which value you get and understand why the conparison failed.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.