Reputation: 81
I've created an entity that has a Sortable behavior and have one question about using it.
The methods for setting and getting positions are not enough for me, so I want to do simple
moveUp and moveDown methods with following code:
public function moveUp() {
++$this->position;
}
public function moveDown() {
if($this->position != 0)
--$this->position;
}
With this implementation the moveUp method has no limit for incrementing up the item with already max position. What is the best way to forbid incrementing such items? I've heard that doing custom queries directly in entities isn't a good practice, so how can I check if the item already has a max value?
Upvotes: 5
Views: 2796
Reputation: 49533
Same problem here, by reading the code I noticed that:
// Compute position if it is negative
if ($newPosition < 0) {
$newPosition += $this->maxPositions[$hash] + 2; // position == -1 => append at end of list
if ($newPosition < 0) $newPosition = 0;
}
(in SortableListener:141)
I guess that by setting -1
as position, it will be moved to the end of the list. And -2
will put it second-to-last.
Edit: Sorry I answered too fast, I also wanted to add:
I don't think you need to limit the position yourself, the SortableListener
will:
// Set position to max position if it is too big
$newPosition = min(array($this->maxPositions[$hash] + 1, $newPosition));
So your moveUp()
function could be (btw did you reverse moveUp
and moveDown
?):
public function moveUp()
{
if ($this->position != 0) {
$this->position--;
}
}
public function moveDown()
{
$this->position++;
}
Update: Well after some testing, it turns out there is a bug in that feature.
setPosition(-1)
will put the object at the end of the list, but it creates a gap in the positions.
I've reproduced it here: https://github.com/l3pp4rd/DoctrineExtensions/pull/908
I hope it will be fixed.
Upvotes: 2
Reputation: 878
well you can have an event listener hooked which would populate SortableMaxAware interface d entities with a max value fetched from the database. This is of course cumbersome, but hey you are using ORM :) have fun.
Upvotes: 0