Web Development. Client Satisfaction. Web Consultancy. Professional. UX. Fast. Responsive Design. Dynamic. Interactive. Innovative. Ecommerce. Wordpress plugins. Prestashop modules. You name it.

How To Make Sortable Drag and drop Using Doctrine Symfony

How To Make Sortable Drag and drop Using Doctrine Symfony

In order to implement this functionality you will need a jquery plugin to make the drag and drop functionality to work. For this tutorial I will use jquery ui the sortable plugin.

Theoretically we must take the next steps do implement this functionality.

  1. Create the list with all posts/list you need to sort.
  2. Create a jquery function using drag and drop plugin to get the new position of the element.
  3. Send the id if your post and the new position to controller in order to update its position in the database

It would be quite difficult to update the position for all posts after a post changed its position, but fortunately we don't need to worry about this thing because doctrine has a lot of nice functions to help us.

Drag and drop doctrine functionality

First of all let's create the jquery function to send the post id and the new position to controller.

  stop:function(event, ui){
  var element_dd = ui.item[0].attributes.element.value,
      position = ui.item.index(),
      link = base_url+'/update/post/'+element_dd;


You will have to change the link var and add yours. Next in the controller file we will have to create the following function to update the post position.

public function update_post_position(Request $request){
  $post_id = $requrest->get('post_id');
  $position = $request->get('position');

  $em = $this->getDoctrine()->getManager();
  $post = $em->getRepository(Post::class)->find($post_id);
      return new jsonresponse(true);
  }catch(\PdoException $e){


I think it's pretty clear what is happening in the above function, now, the last and maybe the most important change we need to do is in the entity class where we will have to create the position column in a specific way. Open you entity file and add the following piece of code:

 * @Gedmo\SortablePosition
* @ORM\Column(name="position", type="integer", length=100)   
private $position;

The above code will make for you the entire functionality of change the position for all the posts after an element changed its position. In order to be able to use the SoratablePosition you will have to install a doctrine extension, anyway it's very easy just look on google how to install it. 
Also you will have to include this in your entity file:

use Gedmo\Mapping\Annotation as Gedmo;

Last thing to do to make this working is when you select your posts to send to the frontend you will have to order them by the new column (position).

Leave a Reply

Notify of