Use Twig’s renderBlock to update a table row with AJAX

So I was developing a page with a table, where one could delete and edit the data on the table. Deleting was simple, it would do an AJAX request to delete, and then I’d remove the table row using jQuery.

But when you edit the row, you would also need to update the row after you did the edit. The table row was already defined in the twig template though, so couldn’t I just reuse it? Yes we can. This is probably rookie beginners stuff, but well, I’m still learning Symfony (and bootstrap, and basically all frontend stuff).

So, to illustrate, I had this piece of template in my page.

With jQuery, I had an event handler on the paginationContainer, to catch the edit button. This would open up a modal where the record can be edited. After that, the save button was pressed, which I was also catching using jQuery.

So this javascript code looked like this:

So the controller needed to just return the table row, as defined in the template at the beginning of the post. The code in the controller was like this:


Use KnpPaginatorBundle just for calculation

I was working on a table in Symfony where I needed to show a table. To add pagination without doing the hard work myself, I added KnpPaginatorBundle to my project. This worked really nice, and I had my tables paginated in no time. I just followed the example on the github page.

But then it gave me an error that looked much like this:

Not all identifier properties can be found in the ResultSetMapping: id

Right. So I googled the error message, and found that it had something to do with Doctrine, that could use Pagination if you select only specific fields of a table. And of course, that’s exactly what I did.

I built a repository class that would give me some results, based on a comprehensive html form. I would store the entire form in the database, to be able to reproduce the search, just by applying the search form again.

When processing the result, I already limited the search results though, using setFirstResult and setMaxResults. So it should be possible to create pagination.

Fortunately, I took a closer look to the paginator bundle, before I continued writing my own paginator code. I started with taking a look at the twig template, to give me inspiration on what variables my paginator should return. But then it seemed to me that KnpPaginatorBundle could do the math for me. All I had to do, is fill some variables my self.

So need to set:

  • the total number of records
  • the number of items on a page
  • the current page

Easy does it!

I ended up with the following code in my controller: