isXmlHttpRequest() public method

It works if your JavaScript library sets an X-Requested-With HTTP header. It is known to work with common JavaScript frameworks:
See also: http://en.wikipedia.org/wiki/List_of_Ajax_frameworks#JavaScript
public isXmlHttpRequest ( ) : boolean
return boolean true if the request is an XMLHttpRequest, false otherwise
 /**
  * @Route("/{applicationId}")
  * @Method({"GET", "POST"})
  * @Template()
  * @param Request $request
  * @param $applicationId
  * @return array
  */
 public function indexAction(Request $request, $applicationId)
 {
     // Validate the $applicationId, throws Exception if invalid.
     $application = $this->getApplication($this->irisEntityManager, $applicationId);
     // Get the Case for this Tenant and put in the session, as it's needed throughout
     $case = $this->getCase($this->irisEntityManager, $application->getCaseId());
     $request->getSession()->set('submitted-case', serialize($case));
     // Create an empty ReferencingGuarantor object.
     $guarantor = new ReferencingGuarantor();
     $guarantor->setCaseId($application->getCaseId());
     // Build the form.
     $form = $this->createForm($this->formType, $guarantor, array('guarantor_decorator' => $this->referencingGuarantorDecoratorBridgeSubscriber->getGuarantorDecorator(), 'attr' => array('id' => 'generic_step_form', 'class' => 'referencing branded individual-guarantor-form', 'novalidate' => 'novalidate')));
     // Process a client round trip, if necessary
     if ($request->isXmlHttpRequest()) {
         $form->submit($request);
         return $this->render('BarbonHostedApiLandlordReferenceBundle:NewReference/Guarantor/Validate:index.html.twig', array('form' => $form->createView()));
     }
     // Submit the form.
     $form->handleRequest($request);
     if ($form->isValid()) {
         $case = $this->getCase($this->irisEntityManager, $application->getCaseId());
         // Dispatch the new guarantor reference event.
         $this->eventDispatcher->dispatch(NewReferenceEvents::GUARANTOR_REFERENCE_CREATED, new NewGuarantorReferenceEvent($case, $application, $guarantor));
         // Send the user to the success page.
         return $this->redirectToRoute('barbon_hostedapi_landlord_reference_newreference_guarantor_confirmation_index', array('applicationId' => $applicationId));
     }
     return array('form' => $form->createView());
 }
 /**
  * Show edit history of an object
  * Required REQUEST parameters are:
  *     objectId - int
  *     objectClass - base64_encoded fully qualified class name
  * 
  * @param Request $request
  * @return \HealthCareAbroad\AdminBundle\Controller\Response
  */
 public function showEditHistoryAction(Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         //throw $this->createNotFoundException("Only supports AJAX request");
     }
     $objectId = $request->get('objectId', null);
     $objectClass = $request->get('objectClass', null);
     if ($objectId === null || $objectClass === null) {
         return new Response("objectId and objectClass are required parameters", 400);
     }
     $objectClass = \base64_decode($objectClass);
     if (!\class_exists($objectClass)) {
         throw $this->createNotFoundException("Cannot view history of invalid class {$objectClass}");
     }
     $object = $this->getDoctrine()->getRepository($objectClass)->find($objectId);
     if (!$object) {
         throw $this->createNotFoundException("Object #{$objectId} of class {$objectClass} does not exist.");
     }
     $service = $this->get('services.log.entity_version');
     $versionEntries = $service->getObjectVersionEntries($object);
     $template = 'InstitutionBundle:History:editHistory.html.twig';
     if ($request->isXmlHttpRequest()) {
         $template = 'InstitutionBundle:History:versionList.html.twig';
     }
     $objectName = $object->__toString();
     return $this->render($template, array('versions' => $versionEntries, 'objectName' => $objectName));
 }
Example #3
0
 /**
  * {@inheritdoc}
  */
 public function render($name, array $parameters = array())
 {
     if ($this->request->isXmlHttpRequest()) {
         return $this->engine->render($name, $parameters);
     }
     if (!$this->admin->inAdmin() || $this->isRender || in_array($name, ['GloryAdminBundle:Security:login.html.twig'])) {
         return $this->engine->render($name, $parameters);
     }
     $this->isRender = true;
     $layoutName = 'GloryAdminBundle::layout.html.twig';
     $template = $this->load($name);
     if (in_array($layoutName, $this->getTemplates($template))) {
         return $this->engine->render($name, $parameters);
     }
     $layout = $this->load($layoutName);
     $blocks = $this->getBlocks($template, $parameters);
     //        $blocks = [];
     //        foreach (['title', 'stylesheets', 'javascripts', 'content'] as $name) {
     //            if (false !== $block = $this->getBlock($template, $name)) {
     //                $blocks[$name] = $block;
     //            }
     //        }
     ob_start();
     try {
         $layout->display($parameters, $blocks);
     } catch (\Exception $e) {
         ob_end_clean();
         throw $e;
     }
     return ob_get_clean();
 }
 public function indexAction(Request $request)
 {
     /** @var $em EntityManager */
     /** @var AssetClassRepository $repo */
     $em = $this->get('doctrine.orm.entity_manager');
     $repo = $em->getRepository('WealthbotAdminBundle:AssetClass');
     /** @var User $ria */
     $ria = $this->getUser();
     $selectedModel = $ria->getRiaCompanyInformation()->getPortfolioModel();
     $riaCompanyInfo = $ria->getRiaCompanyInformation();
     $isShowExpectedAsset = $riaCompanyInfo->getIsShowClientExpectedAssetClass();
     $isShowAccountType = $this->isShowAccountType($riaCompanyInfo);
     $isShowPriority = false;
     //$riaCompanyInfo->isShowSubclassPriority();
     $accountTypes = $em->getRepository('WealthbotRiaBundle:SubclassAccountType')->findAll();
     $assetClasses = $repo->findByModelIdAndOwnerId($selectedModel->getId(), $ria->getId());
     //var_dump($selectedModel->getId(), $assetClasses);die;
     $assets = new AssetCollection($assetClasses, $selectedModel);
     $options = array('original_assets' => $assetClasses, 'original_subclasses' => $this->collectOriginalSubclassesForAssets($assetClasses));
     $form = $this->createForm(new CategoriesFormType($ria, $em), $assets);
     $formHandler = new CategoriesFormHandler($form, $request, $em, $options);
     if ($request->isMethod('post') && $formHandler->process()) {
         if ($request->isXmlHttpRequest()) {
             return $this->getJsonResponse(array('status' => 'success', 'success_url' => $this->generateUrl('rx_ria_dashboard_models_tab', array('tab' => 'categories'))));
         }
         return $this->redirect($this->generateUrl('rx_ria_dashboard_models_tab', array('tab' => 'categories')));
     }
     if ($request->isXmlHttpRequest()) {
         $content = $this->renderView('WealthbotRiaBundle:Categories:index.html.twig', array('form' => $form->createView(), 'is_show_expected_asset' => $isShowExpectedAsset, 'is_show_account_type' => $isShowAccountType, 'is_show_priority' => $isShowPriority, 'is_show_tolerance_band' => $riaCompanyInfo->isRebalancedFrequencyToleranceBand(), 'account_types' => $accountTypes));
         return $this->getJsonResponse(array('status' => 'form', 'content' => $content));
     }
     return $this->render('WealthbotRiaBundle:Categories:index.html.twig', array('form' => $form->createView(), 'is_show_expected_asset' => $isShowExpectedAsset, 'is_show_account_type' => $isShowAccountType, 'is_show_priority' => $isShowPriority, 'is_show_tolerance_band' => $riaCompanyInfo->isRebalancedFrequencyToleranceBand(), 'account_types' => $accountTypes));
 }
 public function indexAction(Request $request)
 {
     /** @var $em EntityManager */
     /** @var AssetClassRepository $repo */
     $em = $this->get('doctrine.orm.entity_manager');
     $repo = $em->getRepository('WealthbotAdminBundle:AssetClass');
     $user = $this->getUser();
     $model = $em->getRepository('WealthbotAdminBundle:CeModel')->find($request->get('model_id'));
     $accountTypes = $em->getRepository('WealthbotRiaBundle:SubclassAccountType')->findAll();
     $assetClasses = $repo->findWithSubclassesByModelIdAndOwnerId($model->getId(), null);
     $assets = new AssetCollection($assetClasses, $model);
     $options = array('original_assets' => $assetClasses, 'original_subclasses' => $this->collectOriginalSubclassesForAssets($assetClasses));
     $form = $this->createForm(new CategoriesFormType($user, $em), $assets);
     $formHandler = new CategoriesFormHandler($form, $request, $em, $options);
     if ($request->isMethod('post') && $formHandler->process()) {
         if ($request->isXmlHttpRequest()) {
             return $this->getJsonResponse(array('status' => 'success', 'success_url' => $this->generateUrl('rx_admin_models_index_strategy', array('slug' => $model->getSlug()))));
         }
         return $this->redirect($this->generateUrl('rx_admin_models_index_strategy', array('slug' => $model->getSlug())));
     }
     if ($request->isXmlHttpRequest()) {
         $content = $this->renderView('WealthbotAdminBundle:Categories:index.html.twig', array('form' => $form->createView(), 'is_show_expected_asset' => true, 'is_show_account_type' => true, 'is_show_priority' => false, 'account_types' => $accountTypes));
         return $this->getJsonResponse(array('status' => 'form', 'content' => $content));
     }
     return $this->render('WealthbotAdminBundle:Categories:index.html.twig', array('form' => $form->createView(), 'is_show_expected_asset' => true, 'is_show_account_type' => true, 'is_show_priority' => false, 'account_types' => $accountTypes));
 }
 public function loginAction(Request $request)
 {
     /** @var $session \Symfony\Component\HttpFoundation\Session\Session */
     $session = $request->getSession();
     // get the error if any (works with forward and redirect -- see below)
     if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
         $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
     } elseif (null !== $session && $session->has(SecurityContext::AUTHENTICATION_ERROR)) {
         $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
         $session->remove(SecurityContext::AUTHENTICATION_ERROR);
     } else {
         $error = '';
     }
     if ($error) {
         // TODO: this is a potential security risk (see http://trac.symfony-project.org/ticket/9523)
         $error = $error->getMessage();
     }
     // last username entered by the user
     $lastUsername = null === $session ? '' : $session->get(SecurityContext::LAST_USERNAME);
     // we register the username in session used in dispatcherLoginFailureResponse
     $session->set('login-username', $lastUsername);
     // we test if the number of attempts allowed connections number with the username have been exceeded.
     if (!empty($lastUsername) && $this->container->has('sfynx.auth.dispatcher.login_failure.change_response')) {
         $key = $this->container->get('sfynx.auth.dispatcher.login_failure.change_response')->getKeyValue();
         if ($key == "stop-client") {
             $session->set('login-username', '');
             $session->remove(SecurityContext::LAST_USERNAME);
             if ($request->isXmlHttpRequest()) {
                 $response = new Response(json_encode('error'));
                 $response->headers->set('Content-Type', 'application/json');
                 return $response;
             } else {
                 $new_url = $this->container->get('router')->generate('fos_user_security_login');
                 $session->getFlashBag()->add('errorform', "you exceeded the number of attempts allowed connections!");
                 return new RedirectResponse($new_url);
             }
         }
     }
     $csrfToken = $this->container->has('form.csrf_provider') ? $this->container->get('form.csrf_provider')->generateCsrfToken('authenticate') : null;
     if ($request->isXmlHttpRequest()) {
         if ($error) {
             $statut = "error";
         } else {
             $statut = "ok";
         }
         $response = new Response(json_encode($statut));
         $response->headers->set('Content-Type', 'application/json');
         return $response;
     }
     return $this->renderLogin(array('last_username' => $lastUsername, 'error' => $error, 'csrf_token' => $csrfToken, 'NoLayout' => $this->container->get('request')->query->get('NoLayout')));
 }
 /**
  * @param Request $request
  *
  * @return \Symfony\Component\HttpFoundation\RedirectResponse|Response
  */
 public function doExecute(Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         return new RedirectResponse($this->getRedirectPath(null));
     }
     return parent::doExecute($request);
 }
 /**
  * Returns all attribute groups as json
  *
  * @param Request $request
  *
  * @return \Symfony\Component\HttpFoundation\JsonResponse|\Symfony\Component\HttpFoundation\RedirectResponse
  */
 public function ajaxIndexAction(Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         return $this->redirectToAction('index');
     }
     return $this->jsonResponse(['sets' => $this->manager->getAttributeGroupSet()]);
 }
Example #9
0
 /**
  * @param $id
  * @param Request $request
  * @return JsonResponse
  */
 public function updateAjaxSessionAction($id, Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         throw new NotFoundHttpException('This action need to be call with AJAX');
     }
     $session = $request->getSession();
     $em = $this->getDoctrine()->getManager();
     $cart = $session->get('carts');
     $json = [];
     $qte = $request->query->get('qte');
     $pu = $request->query->get('pu');
     if ($qte !== null) {
         $cart[$id] = $qte;
         $json['sec'] = sprintf('Nouvelle quantité %s, pour la clé %s', $qte, $id);
         $json['qte'] = $qte;
         $json['totalpu'] = $pu * $qte;
         $session->set('carts', $cart);
         $session->save();
         //Calcul du total
         $products = $this->getProductCart($em, $cart);
         $total = $this->getShopTotal($products, $cart);
         $json['total'] = $total;
     }
     return new JsonResponse(['json' => $json]);
 }
 /**
  * The method that is executed when the user performs a 'edit' action on an entity.
  *
  * @return RedirectResponse|Response
  */
 protected function editAction()
 {
     $this->dispatch(EasyAdminEvents::PRE_EDIT);
     if ($this->request->isXmlHttpRequest()) {
         return $this->ajaxEdit();
     }
     $id = $this->request->query->get('id');
     $entity = $this->findCurrentEntity();
     $fields = $this->entity['edit']['fields'];
     if (method_exists($this, $customMethodName = 'create' . $this->entity['name'] . 'EditForm')) {
         $editForm = $this->{$customMethodName}($entity, $fields);
     } else {
         $editForm = $this->createEditForm($entity, $fields);
     }
     $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
     $editForm->handleRequest($this->request);
     if ($editForm->isValid()) {
         $this->dispatch(EasyAdminEvents::PRE_UPDATE, array('entity' => $entity));
         if (method_exists($this, $customMethodName = 'preUpdate' . $this->entity['name'] . 'Entity')) {
             $this->{$customMethodName}($entity);
         } else {
             $this->preUpdateEntity($entity);
         }
         $this->em->flush();
         $this->dispatch(EasyAdminEvents::POST_UPDATE, array('entity' => $entity));
         $refererUrl = $this->request->query->get('referer', '');
         return !empty($refererUrl) ? $this->redirect(urldecode($refererUrl)) : $this->redirect($this->generateUrl('admin', array('action' => 'list', 'entity' => $this->entity['name'])));
     }
     $this->dispatch(EasyAdminEvents::POST_EDIT);
     return $this->render($this->entity['templates']['edit'], array('form' => $editForm->createView(), 'entity_fields' => $fields, 'entity' => $entity, 'delete_form' => $deleteForm->createView()));
 }
Example #11
0
 public function listAction(Request $request, $filter)
 {
     $user = $this->getUser();
     $em = $this->getDoctrine()->getManager();
     if ($user != null) {
         $request->setLocale($user);
         $listEvent = null;
         $listEvent = $em->getRepository('MdyXlagendaBundle:Event')->listEvents(null);
         return $this->render('MdyXlagendaBundle:Event:list.html.twig', array('listEvent' => $listEvent, 'filter' => $filter));
     } else {
         // utilisateur anonymous
         if ($request->isXmlHttpRequest()) {
             // il s'agit d'un appel AJAX
             if ($request->getMethod() == "POST") {
                 $filter = array();
                 $filter['lieu'] = $request->request->get('lieu');
                 $filter['rubrique'] = $request->request->get('rubrique');
                 $filter['dateDebut'] = $request->request->get('dateDebut');
                 $filter['dateFin'] = $request->request->get('dateFin');
                 $listEvent = $em->getRepository('MdyXlagendaBundle:Event')->findFilter($filter);
                 return $this->render('MdyXlagendaBundle:Event:visitor.ajax.twig', array('listEvent' => $listEvent));
             } else {
             }
         } else {
             // il s'agit d'un appel "standard"
             $listEvent = $em->getRepository('MdyXlagendaBundle:Event')->myFindAll();
             $listLieu = $em->getRepository('MdyXlagendaBundle:Lieu')->findAll();
             $listRubrique = $em->getRepository('MdyXlagendaBundle:Rubrique')->findAll();
             return $this->render('MdyXlagendaBundle:Event:visitor.html.twig', array('listEvent' => $listEvent, 'listLieu' => $listLieu, 'listRubrique' => $listRubrique, 'filter' => null));
         }
     }
 }
 public function needConsoleInjection(Request $request, Response $response)
 {
     if ($request->isXmlHttpRequest() || !$response->headers->has('X-Debug-Token') || '3' === substr($response->getStatusCode(), 0, 1) || $response->headers->has('Content-Type') && false === strpos($response->headers->get('Content-Type'), 'html') || 'html' !== $request->getRequestFormat()) {
         return false;
     }
     return true;
 }
Example #13
0
 /**
  * Get record detailed view
  *
  * @param Application $app
  * @param Request     $request
  *
  * @return JsonResponse
  */
 public function getRecord(Application $app, Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         $app->abort(400);
     }
     $searchEngine = $options = null;
     $train = '';
     if ('' === ($env = strtoupper($request->get('env', '')))) {
         $app->abort(400, '`env` parameter is missing');
     }
     // Use $request->get as HTTP method can be POST or GET
     if ('RESULT' == ($env = strtoupper($request->get('env', '')))) {
         try {
             $options = SearchEngineOptions::hydrate($app, $request->get('options_serial'));
             $searchEngine = $app['phraseanet.SE'];
         } catch (\Exception $e) {
             $app->abort(400, 'Search-engine options are not valid or missing');
         }
     }
     $pos = (int) $request->get('pos', 0);
     $query = $request->get('query', '');
     $reloadTrain = !!$request->get('roll', false);
     $record = new \record_preview($app, $env, $pos < 0 ? 0 : $pos, $request->get('cont', ''), $searchEngine, $query, $options);
     if ($record->is_from_reg()) {
         $train = $app['twig']->render('prod/preview/reg_train.html.twig', ['record' => $record]);
     }
     if ($record->is_from_basket() && $reloadTrain) {
         $train = $app['twig']->render('prod/preview/basket_train.html.twig', ['record' => $record]);
     }
     if ($record->is_from_feed()) {
         $train = $app['twig']->render('prod/preview/feed_train.html.twig', ['record' => $record]);
     }
     return $app->json(["desc" => $app['twig']->render('prod/preview/caption.html.twig', ['record' => $record, 'highlight' => $query, 'searchEngine' => $searchEngine, 'searchOptions' => $options]), "html_preview" => $app['twig']->render('common/preview.html.twig', ['record' => $record]), "others" => $app['twig']->render('prod/preview/appears_in.html.twig', ['parents' => $record->get_grouping_parents(), 'baskets' => $record->get_container_baskets($app['EM'], $app['authentication']->getUser())]), "current" => $train, "history" => $app['twig']->render('prod/preview/short_history.html.twig', ['record' => $record]), "popularity" => $app['twig']->render('prod/preview/popularity.html.twig', ['record' => $record]), "tools" => $app['twig']->render('prod/preview/tools.html.twig', ['record' => $record]), "pos" => $record->get_number(), "title" => str_replace(['[[em]]', '[[/em]]'], ['<em>', '</em>'], $record->get_title($query, $searchEngine))]);
 }
Example #14
0
 public function listAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $objBrowser = new \App\BackendBundle\Utils\Form\Offers\OffersBrowser($request, $this->getUser(), $em);
     $template = $request->isXmlHttpRequest() ? 'AppBackendBundle:Offers:listAjax.html.twig' : 'AppBackendBundle:Offers:list.html.twig';
     return $this->render($template, array('sort_form' => $this->createForm($objBrowser->getSortForm())->createView(), 'filter_form' => $this->createForm($objBrowser->getFilterForm())->createView(), 'browser' => $objBrowser));
 }
 /**
  * Gets the normalized type of a request.
  *
  * The normalized type is a short, lowercase version of the format, such as
  * 'html', 'json' or 'atom'.
  *
  * @param \Symfony\Component\HttpFoundation\Request $request
  *   The request object from which to extract the content type.
  *
  * @return string
  *   The normalized type of a given request.
  */
 public function getContentType(Request $request)
 {
     // AJAX iframe uploads need special handling, because they contain a JSON
     // response wrapped in <textarea>.
     if ($request->get('ajax_iframe_upload', FALSE)) {
         return 'iframeupload';
     }
     // Check all formats, if priority format is found return it.
     $first_found_format = FALSE;
     $priority = array('html', 'drupal_ajax', 'drupal_modal', 'drupal_dialog');
     foreach ($request->getAcceptableContentTypes() as $mime_type) {
         $format = $request->getFormat($mime_type);
         if (in_array($format, $priority, TRUE)) {
             return $format;
         }
         if (!is_null($format) && !$first_found_format) {
             $first_found_format = $format;
         }
     }
     // No HTML found, return first found.
     if ($first_found_format) {
         return $first_found_format;
     }
     if ($request->isXmlHttpRequest()) {
         return 'ajax';
     }
     // Do HTML last so that it always wins.
     return 'html';
 }
 /**
  * Add a comment via ajax call
  *
  * @param Request $request
  * @param $contentId id of content to insert comment
  * @return Response
  */
 public function addCommentAction(Request $request, $contentId)
 {
     if ($request->isXmlHttpRequest()) {
         return $this->container->get('pvr_ezcomment.service')->addComments($contentId);
     }
     return new Response($this->container->get('translator')->trans('Something goes wrong !'), 400);
 }
 /**
  * {@inheritdoc}
  */
 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
 {
     if ($request->isXmlHttpRequest()) {
         return new JsonResponse(['success' => false, 'message' => $exception->getMessageKey()], 401);
     }
     return parent::onAuthenticationFailure($request, $exception);
 }
Example #18
0
 /**
  * Lists all User entities.
  *
  * @Route("/list", name="user_list")
  * @Method("GET")
  */
 public function indexAction(Request $request)
 {
     $em = $this->getDoctrine()->getManager();
     $errorMessage = "";
     $province = Commons::getArrayProvince('Todas las provincias');
     $zona = Commons::getArrayZona('Todas las zonas');
     $type = Commons::getArrayType('Todos los usuarios');
     $s_name = $request->get('s_name', '');
     $s_zona = $request->get('s_zona', '');
     $s_type = $request->get('s_type', '');
     $document_id = $request->get('document_id', '');
     $s_province = $request->get('s_province', '');
     $entities = $em->getRepository('AppBundle:User')->findByRoleAttendant($s_name, $s_zona, $s_type, $s_province, $document_id);
     if ($request->isXmlHttpRequest()) {
         // return json
         return new JsonResponse(array_map(function (User $user) {
             return $user->getId();
         }, $entities));
     }
     $paginator = $this->get('knp_paginator');
     $pagination = $paginator->paginate($entities, $request->get('page', 1), 10);
     if (!$entities) {
         $errorMessage = 'No existen registros guardados';
     }
     return $this->render('AppBundle:User:list.html.twig', ['entities' => $pagination, 'message' => $errorMessage, 'province' => $province, 'zona' => $zona, 'type' => $type, 's_name' => $s_name, 's_zona' => $s_zona, 's_type' => $s_type, 's_province' => $s_province, 'document_id' => $document_id]);
 }
 /**
  * The method that is executed when the user performs a 'edit' action on an entity.
  *
  * @return RedirectResponse|Response
  */
 protected function editAction()
 {
     $this->dispatch(EasyAdminEvents::PRE_EDIT);
     $id = $this->request->query->get('id');
     $easyadmin = $this->request->attributes->get('easyadmin');
     $entity = $easyadmin['item'];
     if ($this->request->isXmlHttpRequest() && ($property = $this->request->query->get('property'))) {
         $newValue = 'true' === strtolower($this->request->query->get('newValue'));
         $fieldsMetadata = $this->entity['list']['fields'];
         if (!isset($fieldsMetadata[$property]) || 'toggle' != $fieldsMetadata[$property]['dataType']) {
             throw new \Exception(sprintf('The type of the "%s" property is not "toggle".', $property));
         }
         $this->updateEntityProperty($entity, $property, $newValue);
         return new Response((string) $newValue);
     }
     $fields = $this->entity['edit']['fields'];
     $editForm = $this->executeDynamicMethod('create<EntityName>EditForm', array($entity, $fields));
     $deleteForm = $this->createDeleteForm($this->entity['name'], $id);
     $editForm->handleRequest($this->request);
     if ($editForm->isValid()) {
         $this->dispatch(EasyAdminEvents::PRE_UPDATE, array('entity' => $entity));
         $this->executeDynamicMethod('preUpdate<EntityName>Entity', array($entity));
         $this->em->flush();
         $this->dispatch(EasyAdminEvents::POST_UPDATE, array('entity' => $entity));
         $refererUrl = $this->request->query->get('referer', '');
         return !empty($refererUrl) ? $this->redirect(urldecode($refererUrl)) : $this->redirect($this->generateUrl('easyadmin', array('action' => 'list', 'entity' => $this->entity['name'])));
     }
     $this->dispatch(EasyAdminEvents::POST_EDIT);
     return $this->render($this->entity['templates']['edit'], array('form' => $editForm->createView(), 'entity_fields' => $fields, 'entity' => $entity, 'delete_form' => $deleteForm->createView()));
 }
Example #20
0
 /**
  * @Route("/", name="homepage")
  * @Template()
  */
 public function indexAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         return $this->render('SensioLabsJobBoardBundle:Includes:job_container.html.twig');
     }
     return array();
 }
Example #21
0
 /**
  * Returns category page template name.
  *
  * @param Request $request
  *
  * @return string
  */
 protected function getCategoryTemplate(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         return 'ONGRDemoBundle:Product:list.html.twig';
     }
     return 'ONGRDemoBundle:Category:category.html.twig';
 }
 /**
  * Get a list to feed datagrid
  * @param Request $request
  * @return Response
  */
 public function listAction(Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         throw $this->createNotFoundException("Not found");
     }
     // GET
     $draw = $request->query->get('draw');
     $start = $request->query->get('start');
     $length = $request->query->get('length');
     $search_string = $request->query->get('search');
     $search_string = $search_string['value'];
     $order_column = $request->query->get('order');
     $order_column = $order_column[0]['column'];
     $order_dir = $request->query->get('order');
     $order_dir = $order_dir[0]['dir'];
     $columns = $request->query->get('columns');
     $em = $this->getDoctrine()->getManager();
     $entities = $em->getRepository($this->repository)->findDataTable($columns, $start, $length, $search_string, $order_column, $order_dir);
     $serializer = $this->get('jms_serializer');
     // Construct JSON
     $data_to_return = array();
     $data_to_return['draw'] = $draw;
     $data_to_return['recordsTotal'] = $entities['count_all'];
     $data_to_return['recordsFiltered'] = $entities['count_filtered'];
     unset($entities['count_all']);
     unset($entities['count_filtered']);
     $data_to_return['data'] = $this->dataTransformer($entities);
     return new Response($serializer->serialize($data_to_return, 'json'));
 }
 /**
  * @param Request $request
  *
  * @return JsonResponse
  */
 public function reactivateAccountAction(Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         throw $this->createAccessDeniedException();
     }
     return new JsonResponse(array('code' => 'success'));
 }
 /**
  *
  * [AJAX] Exclusão de Aquisicao já cadastrado
  * @param integer $idAquisicao
  */
 public function excluirAction(Request $request)
 {
     if (!$request->isXmlHttpRequest()) {
         // Verifica se se trata de uma requisição AJAX
         throw $this->createNotFoundException('Página não encontrada');
     }
     $Aquisicao = $this->getDoctrine()->getRepository('CacicCommonBundle:Aquisicao')->find($request->get('id'));
     if (!$Aquisicao) {
         throw $this->createNotFoundException('Aquisicao não encontrado');
     }
     $em = $this->getDoctrine()->getManager();
     foreach ($Aquisicao->getItens() as $item) {
         $Aquisicao->removeIten($item);
         $em->flush($Aquisicao);
         $sql = "DELETE FROM aquisicoes_software\n                    WHERE id_aquisicao_item = " . $item->getIdAquisicaoItem();
         $stmt = $em->getConnection()->prepare($sql);
         $stmt->execute();
     }
     $sql = "DELETE FROM software_licencas\n                WHERE id_aquisicao = " . $Aquisicao->getIdAquisicao();
     $stmt = $em->getConnection()->prepare($sql);
     $stmt->execute();
     $sql = "DELETE FROM aquisicao_item\n                WHERE id_aquisicao = " . $Aquisicao->getIdAquisicao();
     $stmt = $em->getConnection()->prepare($sql);
     $stmt->execute();
     $em->remove($Aquisicao);
     $em->flush();
     $response = new Response(json_encode(array('status' => 'ok')));
     $response->headers->set('Content-Type', 'application/json');
     return $response;
 }
 /**
  * {@inheritDoc}
  */
 public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
 {
     if ($request->isXmlHttpRequest()) {
         return new Response(json_encode(array('has_error' => true, 'error' => $this->translator->trans($exception->getMessage()))));
     }
     return parent::onAuthenticationFailure($request, $exception);
 }
Example #26
0
 /**
  * @Route("/ajax", name="oktothek_tag_ajax")
  * @Method({"GET", "POST"})
  */
 public function ajaxTagAction(Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         $em = $this->getDoctrine()->getManager();
         if ($request->getMethod() == "GET") {
             $tags = $em->getRepository('AppBundle:Tag')->findAll();
             $json = [];
             foreach ($tags as $tag) {
                 $json[] = $tag->getText();
             }
             return new Response(json_encode($json));
         } else {
             //Posts tag
             $action = $request->request->get('action');
             if ($action = "add") {
                 // add new tag
                 $tag = $em->getRepository('AppBundle:Tag')->findOneBy(['text' => $request->request->get('text')]);
                 if (!$tag) {
                     $tag = new Tag();
                     $tag->setText($request->request->get('text'));
                     $em->persist($tag);
                     $em->flush();
                 }
                 return new Response();
             } else {
                 // delete tag
                 $tag = $em->getRepository('AppBundle:Tag')->findOneBy(['text' => $request->request->get('text')]);
                 $em->remove($tag);
                 $em->flush();
                 return new Response();
             }
         }
     }
     return $this->redirect('oktothek_tag_index');
 }
 public function addAction(Request $request)
 {
     //création de l'objet mois
     $mois = new Mois();
     //si nous avons une requête ajax, elle sera traité ici
     if ($request->isXmlHttpRequest()) {
         $requete = $request->request->get('requete');
         if ($requete == "affichage") {
             //création du formulaire d'ajout d'un mois
             $form = $this->get('form.factory')->create(new MoisType(), $mois);
             return $this->render("SMBLoyerBundle:Mois:add.html.twig", array('form' => $form->createView()));
         } else {
             if ($requete == "ajout") {
                 $libelle = $request->request->get('mois');
                 $mois->setLibelle($libelle);
                 $em = $this->getDoctrine()->getManager();
                 $em->persist($mois);
                 $em->flush();
                 //on envoie la liste des mois
                 $listMois = Mois::listMois($this);
                 return $this->render("SMBLoyerBundle:Mois:index.html.twig", array('listMois' => $listMois));
             }
         }
     } else {
         throw new Exception("Pas de Requete envoyée!", 1);
     }
 }
 /**
  * @param Request $request
  *
  * @return JsonResponse
  * @throws HttpException|AccessDeniedHttpException
  *
  * @Route("/search", name="oro_form_autocomplete_search")
  * AclAncestor("oro_search")
  */
 public function searchAction(Request $request)
 {
     $autocompleteRequest = new AutocompleteRequest($request);
     $validator = $this->get('validator');
     $isXmlHttpRequest = $request->isXmlHttpRequest();
     $code = 200;
     $result = ['results' => [], 'hasMore' => false, 'errors' => []];
     if ($violations = $validator->validate($autocompleteRequest)) {
         /** @var ConstraintViolation $violation */
         foreach ($violations as $violation) {
             $result['errors'][] = $violation->getMessage();
         }
     }
     if (!$this->get('oro_form.autocomplete.security')->isAutocompleteGranted($autocompleteRequest->getName())) {
         $result['errors'][] = 'Access denied.';
     }
     if (!empty($result['errors'])) {
         if ($isXmlHttpRequest) {
             return new JsonResponse($result, $code);
         }
         throw new HttpException($code, implode(', ', $result['errors']));
     }
     /** @var SearchHandlerInterface $searchHandler */
     $searchHandler = $this->get('oro_form.autocomplete.search_registry')->getSearchHandler($autocompleteRequest->getName());
     return new JsonResponse($searchHandler->search($autocompleteRequest->getQuery(), $autocompleteRequest->getPage(), $autocompleteRequest->getPerPage(), $autocompleteRequest->isSearchById()));
 }
 private function chooseMedia(Request $request, $type)
 {
     $response = $this->redirect($this->generateUrl('image_annotator_user_home'));
     // Go home if bad type
     $prefix = "";
     if ($request->isXmlHttpRequest()) {
         $prefix = "ajax.";
     }
     /*
      * $path = array('url' => null, '_route' => $request->attributes->get('_route'), '_route_params' => $request->attributes->get('_route_params') );
      */
     $path = array('url' => null);
     switch ($type) {
         case MediaChooserGatewayController::TYPE_ALL:
             $response = $this->forward('ImageAnnotatorBundle:AddFileGateway:gateway', $path);
             break;
         case MediaChooserGatewayController::TYPE_UPLOAD_IMAGE:
             $response = $this->forward('ImageAnnotatorBundle:AddFileGateway:addImage', $path);
             break;
         case MediaChooserGatewayController::TYPE_UPLOAD_GOOGLE:
             $response = $this->forward('ImageAnnotatorBundle:AddFileGateway:addImageGoogle', $path);
             break;
         case MediaChooserGatewayController::TYPE_UPLOAD_FLICKR:
             $response = $this->forward('ImageAnnotatorBundle:AddFileGateway:addImageFlickr', $path);
             break;
     }
     $this->get('session')->set('mediaChooseFinished', false);
     return $response;
 }
Example #30
0
 public function RefreshNotificationAction($id, Request $request)
 {
     if ($request->isXmlHttpRequest()) {
         // si on appele depuis une requette ajax
         $em = $this->getDoctrine()->getManager();
         $Allnotifs = $em->getRepository('OCNotificationBundle:Notification')->findByPourAgent($id);
         if ($Allnotifs) {
             $notifs = array();
             foreach ($Allnotifs as $notif) {
                 $interval = $notif->getDateCreation()->diff(new \DateTime('now'));
                 if ($interval->format('%a') == "0") {
                     $date = "aujourd'hui";
                 } elseif ($interval->format('%a') == "1") {
                     $date = "hier";
                 } else {
                     $date = $interval->format('%a jours');
                 }
                 if ($notif->getEventAssocie() !== null) {
                     $nom_agent = $notif->getEventAssocie()->getAgent()->getNomCanonique();
                 } else {
                     $nom_agent = $notif->getHSFAssocie()->getAgent()->getNomCanonique();
                 }
                 $notifs[$notif->getId()] = array($notif->getId(), $nom_agent, $notif->getTitle(), $notif->getVisionee(), $date);
             }
         } else {
             $notif = null;
         }
         //var_dump($notifs);
         //die();
         $response = new JsonResponse();
         return $response->setData(array('notifs' => $notifs));
     } else {
         throw new Exception("Vous n'etes pas censés être ici ! Cassez vous !");
     }
 }