Symfony 3.1 + Doctrine GEDMO 拡張を使用しています (StofDoctrineExtensionsBundle 経由)。エンティティが Sortable 動作になるように設定しました。
<?php
namespace AppBundle\Entity\Manual;
use AppBundle\Entity\Identifier;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* @ORM\Table(name="manual_pages")
* @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
*/
class Manual
{
use Identifier;
/**
* @ORM\Column(type="string")
* @Assert\NotBlank(message="Toto pole musí být vyplněno")
*/
private $title;
/**
* @ORM\Column(type="text")
* @Assert\NotBlank(message="Toto pole musí být vyplněno")
*/
private $content;
/**
* @ORM\OneToMany(targetEntity="AppBundle\Entity\Manual\ManualImage", mappedBy="manual")
* @ORM\OrderBy({"position"="ASC"})
*/
private $images;
/**
* @Gedmo\SortablePosition
* @ORM\Column(type="integer", nullable=false)
*/
private $position;
/**
* @return mixed
*/
public function getPosition()
{
return $this->position;
}
/**
* @param mixed $position
*/
public function setPosition($position)
{
$this->position = $position;
}
/**
* @return mixed
*/
public function getTitle()
{
return $this->title;
}
/**
* @param mixed $title
*/
public function setTitle($title)
{
$this->title = $title;
}
/**
* @return ManualImage[]
*/
public function getImages()
{
return $this->images;
}
/**
* @param ManualImage[] $images
*/
public function setImages($images)
{
$this->images = $images;
}
/**
* @return mixed
*/
public function getContent()
{
return $this->content;
}
/**
* @param mixed $content
*/
public function setContent($content)
{
$this->content = $content;
}
}
位置を1つずつ変更すると、ソート動作は正常に動作します:
$entity->setPosition($entity->getPosition() + 1);
// or
$entity->setPosition($entity->getPosition() - 1);
しかし、JS ドラッグ & ドロップを実装して位置を変更すると、全体が奇妙になります。たとえば、次の表があるとします。
id | position
1 | 0
2 | 1
3 | 2
4 | 3
5 | 4
6 | 5
ID 6の行に対してこれを行うと:
$newPosition = $entity->getPosition() - 5; // = 0
$entity->setPosition($newPosition);
テーブルは次のように変わります。
id | position
1 | 2
2 | 3
3 | 4
4 | 5
5 | 5
6 | 0
位置 1 には何もありませんが、位置 5 は 2 回占有されています。何か案は?