<?php
namespace App\Controller;
use App\Admin\AttributeGroupAdmin;
use App\Entity\AttributeGroup;
use Pix\SortableBehaviorBundle\Services\PositionHandler;
use Sonata\AdminBundle\Controller\CRUDController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\Routing\Annotation\Route;
class AdminAttributeGroupController extends CRUDController
{
/** @var AttributeGroupAdmin */
protected $admin;
public function setparentAction($parentId, $nextPage)
{
$parentId = (int)$parentId;
$parent = $this->admin->getRepository()->find($parentId);
if (empty($parent)) {
return new RedirectResponse($this->admin->generateUrl($nextPage));
}
/** @var Session $session */
$session = $this->container->get('session');
$session->set(AttributeGroupAdmin::SESSION_PARENT_ID_NAME, $parentId);
return new RedirectResponse($this->admin->generateUrl($nextPage));
}
public function resetparentAction($nextPage)
{
/** @var Session $session */
$session = $this->container->get('session');
$session->remove(AttributeGroupAdmin::SESSION_PARENT_ID_NAME);
return new RedirectResponse($this->admin->generateUrl($nextPage));
}
/**
* Move element
*
* @param string $position
*
* @return RedirectResponse|\Symfony\Component\HttpFoundation\Response
*/
public function moveAction($position)
{
/** @var AttributeGroup $attributeGroup */
$attributeGroup = $this->admin->getSubject();
/** @var AttributeGroupAdmin\ $admin */
$admin = $this->admin;
if (!$this->isXmlHttpRequest()) {
return $this->renderJson(array(
'result' => 'ok',
'objectId' => $this->admin->getNormalizedIdentifier($attributeGroup)
));
}
$currentPosition = $attributeGroup->getPosition();
$position = (int)$position;
$numberOfMoves = $position - $currentPosition;
if (empty($numberOfMoves)) {
return $this->renderJson(array(
'result' => 'ok',
'objectId' => $this->admin->getNormalizedIdentifier($attributeGroup)
));
}
$repository = $admin->getRepository();
if ($numberOfMoves > 0) {
$repository->moveDown($attributeGroup, $numberOfMoves);
} else {
$numberOfMoves = abs($numberOfMoves);
$repository->moveUp($attributeGroup, $numberOfMoves);
}
$attributeGroups = $repository->findBy(['parent' => $attributeGroup->getParent()], ['lft' => 'ASC']);
$order = 0;
foreach ($attributeGroups as $item) {
$item->setPosition($order);
$this->getDoctrine()->getManager()->persist($item);
$this->getDoctrine()->getManager()->flush();
$order++;
}
return $this->renderJson(array(
'result' => 'ok',
'objectId' => $this->admin->getNormalizedIdentifier($attributeGroup)
));
}
}