Finalmix6
Finalmix6

Reputation: 415

Symfony 3/4 : KpnPaginator done through AJAX

I am currently enhancing my skills on Symfony 4. And I'm stuck on a little issue.

I have a website, which is a blog listing articles.

I wanted to add a pagination on it, so I checked for KpnPaginator, and it's working very great.


Here is the code,

The Controller :

 /**
 * @Route("/blog", name="blog")
 * @param ArticleRepository $repo
 * @param Request $request
 * @param PaginatorInterface $paginator
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function index(ArticleRepository $repo, Request $request, PaginatorInterface $paginator)
{

    /*
     *  $repo = $this->getDoctrine()->getRepository(Article::class);
     */

    $articlesQuery = $repo->findAll();


    // Paginate the results of the query
    $articles = $paginator->paginate(
    // Doctrine Query, not results
        $articlesQuery,
        // Define the page parameter
        $request->query->getInt('page', 1),
        // Items per page
        5
    );

    return $this->render('blog/index.html.twig', [
        'controller_name' => 'BlogController',
        'articles' => $articles
    ]);
}

The view :

{% extends 'base.html.twig' %}

{% block title %}Hello {{ controller_name }}!{% endblock %}

{% block body %}
<section class="articles" id="">

    {% for article in articles %}
        <article>
            <h2>{{ article.title }}</h2>
            <div class="metadata">Written on {{ article.createdAt | date('d/m/Y') }}
                at {{ article.createdAt | date('H:i') }}, in Politic Category
            </div>
            <div class="content"><img src="{{ article.image }}" alt="">{{ article.content | raw }}
                <a href="{{ path('blog_show', {'id': article.id}) }}" class="btn btn-primary">Read moree</a>
            </div>
        </article>
    {% endfor %}
</section>
<br>
{{ knp_pagination_render(articles) }}
{% endblock %}

My question is,

How can I make it work through an ajax request?

Like, Once I click on the link, it doesn't refresh the page, but load the content dynamically?

Upvotes: 3

Views: 1740

Answers (1)

Shaun
Shaun

Reputation: 546

You need to setup an onclick handler in JavaScript that makes an AJAX call to your ArticleController.

You can use something like this:

$(document).ready(function() {

var $div = $('.articles');

$.ajax({
    method: 'GET',
    url: '/api/articles' + window.location.search,
    headers: {
        'Accept':'application/json',
        'Content-Type':'application/json'
    },
    dataType: 'json',
    success: function(data){
        $.each(data.items, function(key, article) {
            var html = articleTemplate(article);
            $div.append($.parseHTML(html));
        });
    }
});
});

const articleTemplate = (article) =>
`<article>
        <h2>${ article.title }</h2>
        <div class="metadata">Written on ${ article.createdAt }}
            at ${ article.createdAt }, in Politic Category
        </div>
        <div class="content"><img src="${ article.image }" alt="">${ article.content }
            <a href="{{ Routing.generate('blog_show', {'id': article.id}) }}" class="btn btn-primary">Read more</a>
        </div>
    </article>`;

This is using an ES6 JavaScript template string to update the HTML on your page, so you can remove this part from your Twig template. You will also need to install FOSJSRoutingBundle if you want to use routes in your JavaScript - https://symfony.com/doc/master/bundles/FOSJsRoutingBundle/index.html

You will need to make your ArticleController return a JSON response that the JavaScript handler will use to update the page.

Upvotes: 4

Related Questions