Change position of page in menu, in ajax

@throws AccessDeniedException
@param number $pageId
@param string $menuName
@param number $newPosition
@return Response
518845
public function changePositionAction($pageId, $menuName, $newPosition)
    {
        if ($this->getRequest()->isXmlHttpRequest())
        {
            $pageMenuRepo = $this->getDoctrine()->getRepository('FulgurioLightCMSBundle:PageMenu');
            $pageMenu = $pageMenuRepo->findOneBy(array('page' => $pageId, 'label' => $menuName));
            if ($pageMenu)
            {
                if ($newPosition == $pageMenu->getPosition())
                {
                    // No change
                }
                else if ($newPosition > $pageMenu->getPosition())
                {
                    if ($newPosition <= $pageMenuRepo->getLastMenuPosition($pageMenu->getLabel()))
                    {
                        // Down !
                        $pageMenuRepo->upMenuPagesPosition($pageMenu->getLabel(), $pageMenu->getPosition() + 1, $newPosition);
                        $pageMenu->setPosition($newPosition);
                        $em = $this->getDoctrine()->getManager();
                        $em->persist($pageMenu);
                        $em->flush();
                    }
                }
                else if ($pageMenu->getPosition() > 1)
                {
                    // Up !
                    $pageMenuRepo->downMenuPagesPosition($pageMenu->getLabel(), $newPosition, $pageMenu->getPosition());
                    $pageMenu->setPosition($newPosition);
                    $em = $this->getDoctrine()->getManager();
                    $em->persist($pageMenu);
                    $em->flush();
                }
                else {
                    // doesn t happen
                }
            }
            return new Response();
        }
        throw new AccessDeniedException();
    }
100460
public void replaceElement(final CmsContainerPageElementPanel elementWidget, final String elementId) {

        final CmsRpcAction<CmsContainerElementData> action = new CmsRpcAction<CmsContainerElementData>() {

            @Override
            public void execute() {

                start(500, true);
                getContainerpageService().replaceElement(
                    getData().getRpcContext(),
                    getData().getDetailId(),
                    getRequestParams(),
                    elementWidget.getId(),
                    elementId,
                    getPageState(),
                    getLocale(),
                    this);
            }

            @Override
            protected void onResponse(CmsContainerElementData result) {

                stop(false);

                if (result != null) {
                    // cache the loaded element
                    m_elements.put(result.getClientId(), result);
                    try {
                        replaceContainerElement(elementWidget, result);
                        resetEditButtons();
                        addToRecentList(result.getClientId(), null);
                        setPageChanged(new Runnable() {

                            public void run() {

                                // nothing to do

                            }
                        });
                    } catch (Exception e) {
                        // should never happen
                        CmsDebugLog.getInstance().printLine(e.getLocalizedMessage());
                    }
                }
            }
        };

        if (!isGroupcontainerEditing()) {

            lockContainerpage(new I_CmsSimpleCallback<Boolean>() {

                public void execute(Boolean arg) {

                    if (arg.booleanValue()) {
                        action.execute();
                    }
                }
            });

        } else {
            action.execute();
        }
    }
324302
public function createFromPageAction(Request $request, $rootId, $pageId)
    {
        $rootNode = $this->admin->getObject($rootId);

        if (!$rootNode) {
            throw new NotFoundHttpException(sprintf('unable to find the Menu with id : %s', $rootId));
        }

        $page = $this->get('networking_init_cms.page_manager')->find($pageId);

        if (!$page) {
            throw new NotFoundHttpException(sprintf('unable to find the Page with id : %s', $pageId));
        }

        $menuItem = new MenuItem();

        $menuItem->setPage($page);
        $menuItem->setRoot($rootNode);
        $menuItem->setParent($rootNode);
        $menuItem->setName($page->getTitle());

        $em = $this->getDoctrine()->getManager();
        $em->persist($menuItem);
        $em->flush();

        $this->admin->createObjectSecurity($menuItem);

        return $this->redirect(
            $this->admin->generateUrl('list', ['page_id' => $page->getId(), 'menu_id' => $menuItem->getId()]).'#end'
        );
    }
214443
void setResponsePanelPosition(ResponsePanelPosition position) {
		validateNotNull(position, "position");

		requestTabIndex = getCurrentRequestTabIndex();

		responsePanelPosition = position;
		if (layout == Layout.FULL) {
			updateFullLayout();
			return;
		}

		Component currentTabbedPanel = componentMaximiser.getMaximisedComponent();
		if (componentMaximiser.isComponentMaximised()) {
			componentMaximiser.unmaximiseComponent();
		}

		boolean selectRequest = removeSplitRequestAndResponsePanel(tabbedWork);

		switch (position) {
		case PANEL_ABOVE:
			splitResponsePanelWithWorkTabbedPanel(JSplitPane.VERTICAL_SPLIT);
			break;
		case PANELS_SIDE_BY_SIDE:
			splitResponsePanelWithWorkTabbedPanel(JSplitPane.HORIZONTAL_SPLIT);
			break;
		case TAB_SIDE_BY_SIDE:
			splitResponsePanelWithRequestPanel(JSplitPane.HORIZONTAL_SPLIT, tabbedWork);

			getPaneWork().removeAll();
			getPaneWork().add(getTabbedWork());
			getPaneWork().validate();
			break;
		case TABS_SIDE_BY_SIDE:
		default:
			if (currentTabbedPanel == responseTabbedPanel) {
				currentTabbedPanel = tabbedWork;
			}
			insertResponseTab(tabbedWork);

			getPaneWork().removeAll();
			getPaneWork().add(getTabbedWork());
			getPaneWork().validate();
		}

		if (selectRequest || getTabbedWork().getSelectedComponent() == null) {
			getTabbedWork().setSelectedComponent(
					responsePanelPosition == ResponsePanelPosition.TAB_SIDE_BY_SIDE
							? splitRequestAndResponsePanel
							: requestPanel);
		}

		if (currentTabbedPanel != null) {
			componentMaximiser.maximiseComponent(currentTabbedPanel);
		}
	}
1066308
public function addAction(Request $request, $menuid)
    {
        return parent::doAddAction($this->getAdminListConfigurator($request, $menuid), null, $request);
    }
434321
public function pageSettingsAction($id = null, $uniqid = null)
    {
        /** @var Request $request */
        $request = $this->container->get('request_stack')->getCurrentRequest();
        // the key used to lookup the template
        $templateKey = 'edit';

        if ($id === null) {
            $id = $request->get($this->admin->getIdParameter());
        }

        $object = $this->admin->getObject($id);

        if (!$object) {
            throw new NotFoundHttpException(sprintf('unable to find the object with id : %s', $id));
        }

        if (false === $this->admin->isGranted('EDIT', $object)) {
            throw new AccessDeniedException();
        }

        $this->admin->setSubject($object);

        /** @var $form \Symfony\Component\Form\Form */
        $form = $this->admin->getForm();
        $form->setData($object);

        $view = $form->createView();

        // set the theme for the current Admin Form
        $this->setFormTheme($view, $this->admin->getFormTheme());

        return $this->renderWithExtraParams(
            $this->admin->getTemplate($templateKey),
            [
                'action' => 'edit',
                'form' => $view,
                'object' => $object,
                'language' => \Locale::getDisplayLanguage($object->getLocale()),
            ]
        );
    }
1238786
public function changeImportPositionAction()
    {
        $authResponse  = $this->checkAuth([AdminResources::IMPORT], [], [AccessManager::UPDATE]);
        if ($authResponse !== null) {
            return $authResponse;
        }

        $query = $this->getRequest()->query;

        $this->dispatch(
            TheliaEvents::IMPORT_CHANGE_POSITION,
            new UpdatePositionEvent(
                $query->get('id'),
                $this->matchPositionMode($query->get('mode')),
                $query->get('value')
            )
        );

        return $this->generateRedirectFromRoute('import.list');
    }
695548
public function updatePosition($id, $newPosition = 1)
    {
        $model = $this->makeModel(false);

        if ( ! ($model = $model->find($id))) {
            return false;
        }

        $this->checkModelHasListify($model);

        /** @var ListifyInterface $model */
        $model->setListPosition( (int) $newPosition );

        return $model;
    }
48907
public function changePositionAction()
    {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest())
        {
            $em = $this->getDoctrine()->getManager();
            $pageRepository = $this->getDoctrine()->getRepository('FulgurioLightCMSBundle:Page');
            $page = $this->getPage($request->request->get('pageId'));
            $parentId = $request->request->get('parentId');
            $position = $request->request->get('position');
            if ($parentId != $page->getParent()->getId())
            {
                $pageRepository->downPagesPosition($parentId, $position);
                $pageRepository->upPagesPosition($page->getParent(), $page->getPosition() + 1);
                $page->setParent($pageRepository->find($parentId));
                $models = $this->container->getParameter('fulgurio_light_cms.models');
                $formHandlerClassName = isset($models[$page->getModel()]['back']['handler']) ? $models[$page->getModel()]['back']['handler'] : '\Fulgurio\LightCMSBundle\Form\Handler\AdminPageHandler';
                $formHandler = new $formHandlerClassName();
                $formHandler->setDoctrine($this->getDoctrine());
                $formHandler->makeFullpath($page);
                $em->persist($page);
                $em->flush();
            }
            else
            {
                if ($position > $page->getPosition())
                {
                    $pageRepository->upPagesPosition($page->getParent(), $page->getPosition() + 1, $position - 1);
                    --$position;
                }
                else
                {
                    $pageRepository->downPagesPosition($page->getParent(), $position, $page->getPosition() - 1);
                }
            }
            $page->setPosition($position);
            $em->persist($page);
            $em->flush();
            $response = new Response(json_encode(array('code' => 42)));
            $response->headers->set('Content-Type', 'application/json');
            return $response;
        }
        throw new AccessDeniedException();
    }
793457
public function setMenuId( $menuId )
    {
        $this->menuId = empty( $menuId ) ? null : (int) $menuId;

        if ( null !== $this->_menu &&
             $this->_menu->id != $this->menuId )
        {
            $this->_menu = null;
        }

        return $this;
    }
29172
public function editAddressBook($id, $newName)
    {
        if (empty($newName) || empty($id)) {
            return $this->handleError('Empty new name or book id');
        }

        $data = array('name' => $newName);
        $requestResult = $this->sendRequest('addressbooks/' . $id, 'PUT', $data);

        return $this->handleResult($requestResult);
    }
243083
public function paging($pageNum, $pageSize) {
        $offset = ($pageNum - 1) * $pageSize;
        $this->statementContext->setLimit("{$offset}, {$pageSize}");
        return $this;
    }
944872
public function moveInto(NodeInterface $referenceNode, string $newName = null): void
    {
        if ($referenceNode === $this || $referenceNode === $this->getParent()) {
            return;
        }

        if ($this->isRoot()) {
            throw new NodeException('The root node cannot be moved.', 1346769001);
        }

        $name = $newName !== null ? $newName : $this->getName();

        if ($referenceNode !== $this->getParent() && $referenceNode->getNode($name) !== null) {
            throw new NodeExistsException(sprintf('Node with path "%s" already exists.', $name), 1292503470);
        }

        if (($referenceNode instanceof Node && !$referenceNode->willChildNodeBeAutoCreated($name)) && !$referenceNode->isNodeTypeAllowedAsChildNode($this->getNodeType())) {
            throw new NodeConstraintException(sprintf('Cannot move %s into %s', $this, $referenceNode), 1404648124);
        }

        $this->emitBeforeNodeMove($this, $referenceNode, NodeDataRepository::POSITION_LAST);
        $this->setPath(NodePaths::addNodePathSegment($referenceNode->getPath(), $name));
        $this->nodeDataRepository->persistEntities();

        $this->nodeDataRepository->setNewIndex($this->nodeData, NodeDataRepository::POSITION_LAST);
        $this->context->getFirstLevelNodeCache()->flush();
        $this->emitAfterNodeMove($this, $referenceNode, NodeDataRepository::POSITION_LAST);
        $this->emitNodeUpdated($this);
    }
165391
public static MenuItem newMenuItem(final Class<? extends Page> pageClass,
		final String resourceModelKey, final Component component, final PageParameters parameters)
	{
		final BookmarkablePageLink<String> bookmarkablePageLink = new BookmarkablePageLink<>(
			MenuPanel.LINK_ID, pageClass, parameters);
		final IModel<String> labelModel = ResourceModelFactory.newResourceModel(resourceModelKey,
			component);
		final MenuItem menuItem = new MenuItem(bookmarkablePageLink, labelModel);
		return menuItem;
	}
171245
public function editPage($page_id = null)
    {
        $this->setPage($page_id);
        $this->setTitleEditPage();
        $this->setBreadcrumbEditPage();

        $this->setData('page', $this->data_page);
        $this->setData('languages', $this->language->getList(array('enabled' => true)));

        $this->submitEditPage();
        $this->setDataImagesEditPage();
        $this->setDataCategoriesEditPage();
        $this->outputEditPage();
    }
173363
final public function move($nextpageid=null, $prevpageid=null) {
        global $DB;
        if ($nextpageid === null) {
            $nextpageid = $this->properties->nextpageid;
        }
        if ($prevpageid === null) {
            $prevpageid = $this->properties->prevpageid;
        }
        $obj = new stdClass;
        $obj->id = $this->properties->id;
        $obj->prevpageid = $prevpageid;
        $obj->nextpageid = $nextpageid;
        $DB->update_record('lesson_pages', $obj);
    }
92195
public function reorderBlocksAction()
	{
		$this->isPostRequest();
		$this->checkLock();

		$placeHolderName = $this->getRequestParameter('place_holder_id');

		$pageRequest = $this->createPageRequest();

		$placeHolder = $pageRequest->getPlaceHolderSet()
				->getFinalPlaceHolders()
				->offsetGet($placeHolderName);

		if ($placeHolder === null) {
			throw new \InvalidArgumentException(sprintf(
					'Placeholder [%s] not found in placeholders set.',
					$placeHolderName
			));
		}

		$blockSet = $pageRequest->getBlockSet()
				->getPlaceHolderBlockSet($placeHolder);

		$blockPositionMap = array_values($this->getRequestParameter('order', array()));

		if ($blockSet->count() !== count($blockPositionMap)) {
			// JS error or data spoofing
			throw new \UnexpectedValueException('Ordered elements and actual blocks count does not match.');
		}

		foreach ($blockPositionMap as $position => $id) {
			
			$block = $blockSet->findById($id);
			
			if ($block === null) {
				throw new \UnexpectedValueException(sprintf('Block [%s] not found.'));
			}

			$block->setPosition($position);
		}

		$this->getEntityManager()
				->flush();

		return new SupraJsonResponse();
	}