1

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 !

5
  • Can you show how you call your page ? Commented Nov 13, 2015 at 14:25
  • Ty, but i wanted to see the link you're using to access your page. :) Commented Nov 13, 2015 at 15:47
  • I edited again. Ty ! Commented Nov 13, 2015 at 16:46
  • So any idea please ? Commented Nov 14, 2015 at 16:12
  • Yeah i have an idea but i am on my phone and it is definitely not easy to answer. I post my as soon as I am on a Pc Commented Nov 15, 2015 at 1:07

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Your method send me the following error : LIMIT argument offset=-5 is not valid. And i don't understand why my argument is negative here...
Yeah that proves that it works better. I edited my answer with the second problem
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.

6 Comments

I have still the same error with \d+ and apparently the int() doesn't work on my repository
You have to clear the cache if you are not in debug mode. Sorry it was intval() function. I have updated the answer.
Always the same error... You think there's no problem with my request?
Just a little question : How many products do you have in your database ?
@Flushdrew, depends, what do you have if you echoed your variable $page? dump($page); or var_dump($page); then exit; to display only this data?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.