5

In my webapplication I have the following category structure:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Category
 *
 * @ORM\Table(name="category", indexes={@ORM\Index(name="fk_category_category_idx", columns={"parent_category_id"})})
 * @ORM\Entity(repositoryClass="AppBundle\Repository\CategoryRepository")
 */
class Category
{
    /**
     * @var string
     *
     * @ORM\Column(name="name", type="string", length=255, nullable=false)
     */
    private $name;

    /**
     * @var boolean
     *
     * @ORM\Column(name="enabled", type="boolean", nullable=false)
     */
    private $enabled = true;

    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var \AppBundle\Entity\Category
     *
     * @ORM\ManyToOne(targetEntity="AppBundle\Entity\Category")
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="parent_category_id", referencedColumnName="id")
     * })
     */
    private $parentCategory;
}

A category can be a parent category or a subcategory of a parent.

Now I would like to add the possibility to change the order of display of only the parent categories.

How could this easily in Sonata Admin?

nielsv
  • 6,540
  • 35
  • 111
  • 215
  • Maybe you can clarify what you want to achieve? Do you mean you want to add some field that will be used for ordering but edit this only for parent categories? Do you want to edit order that are categories are displayed in admin list? Something else entirely? – Aurelijus Rozenas Nov 28 '18 at 08:40
  • What you are doing is basically a many-to-one self-referencing. You have an exemple with a Category entity on the doctrine documentation (https://www.doctrine-project.org/projects/doctrine-orm/en/2.6/reference/association-mapping.html#one-to-many-self-referencing). Now about your issue, can you be a little bit more clear? – fgamess Nov 28 '18 at 09:52

1 Answers1

1

This model is self join with relationship (Many To One).

Even though, you want change order only to the parents category, you need to create one more field as below.

 /**
 * @var integer
 *
 * @ORM\Column(name="sort", type="integer", options={"unsigned"=true})
 */
 private $sort = 0; 

This field will have default sort value of 0 and you can order by DESC of sort column. So higher value parent category will be in top and sorted based on sort values.

Bala
  • 913
  • 9
  • 18