Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering entities with sortable behavior in Doctrine 2 (Symfony 2)

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?

like image 619
TrueDrago Avatar asked Nov 04 '22 05:11

TrueDrago


1 Answers

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.

like image 183
Matthieu Napoli Avatar answered Nov 15 '22 04:11

Matthieu Napoli