当前位置: 首页>>代码示例>>PHP>>正文


PHP Request::getSession方法代码示例

本文整理汇总了PHP中Symfony\Component\HttpFoundation\Request::getSession方法的典型用法代码示例。如果您正苦于以下问题:PHP Request::getSession方法的具体用法?PHP Request::getSession怎么用?PHP Request::getSession使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在Symfony\Component\HttpFoundation\Request的用法示例。


在下文中一共展示了Request::getSession方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。

示例1: editAction

 /**
  * @Route("/taches/edition/{slug}")
  * @Template()
  */
 public function editAction($slug, Request $request)
 {
     if (!empty($slug)) {
         $session = $request->getSession();
         //0 valeur par defaut si vide
         $id_user = $session->get('user', 0);
         if ($id_user == 0) {
             $request->getSession()->getFlashBag()->add('error', 'OULAH ! Il s\'est passé un truc pas net O.o. Tu t\'es déco ?');
             return $this->redirect($this->generateUrl('corvee_taches_homepage', array()));
         }
         $em = $this->getDoctrine()->getManager();
         $tache = $em->getRepository('Corvees\\TachesBundle\\Entity\\Tache')->findOneBySlug($slug);
         if (!empty($tache)) {
             $user = $em->getRepository('Corvees\\TachesBundle\\Entity\\User')->find($id_user);
             $tache->setFkIntervenant($user);
             $tache->setDateEffectue(new \Datetime());
             $form = $this->get('form.factory')->create(new TacheEditType(), $tache);
             if ($form->handleRequest($request)->isValid()) {
                 $difference = $tache->getDateCreation()->diff($tache->getDateEffectue());
                 $difference = $difference->format("%Y-%m-%d %H:%i:%s");
                 $difference = new \DateTime($difference);
                 $tache->setTemps($difference);
                 $em = $this->getDoctrine()->getManager();
                 $em->persist($tache);
                 $em->flush();
                 $request->getSession()->getFlashBag()->add('notice', 'Tache bien enregistrée.');
                 return $this->redirect($this->generateUrl('corvee_taches_homepage', array()));
             }
             return array('form' => $form->createView(), 'tache' => $tache, 'route' => 'formulaire_tache_edit');
         }
     }
 }
开发者ID:pandorz,项目名称:gestionCorvees,代码行数:36,代码来源:TachesController.php

示例2: onLogoutSuccess

 /**
  * @param Request $request
  * @return null|RedirectResponse
  */
 public function onLogoutSuccess(Request $request)
 {
     // Chamilo logout
     $request->getSession()->remove('_locale');
     $request->getSession()->remove('_locale_user');
     if (api_is_global_chat_enabled()) {
         $chat = new \Chat();
         $chat->setUserStatus(0);
     }
     $userId = $this->storage->getToken()->getUser()->getId();
     $tbl_track_login = Database::get_main_table(TABLE_STATISTIC_TRACK_E_LOGIN);
     $sql = "SELECT login_id, login_date\n                FROM {$tbl_track_login}\n                WHERE login_user_id = {$userId}\n                ORDER BY login_date DESC\n                LIMIT 0,1";
     $row = Database::query($sql);
     $loginId = null;
     if (Database::num_rows($row) > 0) {
         $loginId = Database::result($row, 0, "login_id");
     }
     $loginAs = $this->checker->isGranted('ROLE_PREVIOUS_ADMIN');
     if (!$loginAs) {
         $current_date = api_get_utc_datetime();
         $sql = "UPDATE {$tbl_track_login}\n                    SET logout_date='" . $current_date . "'\n        \t\t    WHERE login_id='{$loginId}'";
         Database::query($sql);
     }
     $online_table = Database::get_main_table(TABLE_STATISTIC_TRACK_E_ONLINE);
     $query = "DELETE FROM " . $online_table . " WHERE login_user_id = {$userId}";
     Database::query($query);
     require_once api_get_path(SYS_PATH) . 'main/chat/chat_functions.lib.php';
     exit_of_chat($userId);
     $login = $this->router->generate('home');
     $response = new RedirectResponse($login);
     return $response;
 }
开发者ID:omaoibrahim,项目名称:chamilo-lms,代码行数:36,代码来源:LogoutSuccessHandler.php

示例3: filesAction

 /**
  * filesAction
  *
  * @param Request $request
  * @param int     $pageId
  *
  * @return Response
  */
 public function filesAction(Request $request, $pageId)
 {
     $uploadDir = trim($this->container->getParameter('kr_solutions_krcms.upload_dir'));
     $_SESSION['KCFINDER'] = array();
     $_SESSION['KCFINDER']['disabled'] = false;
     $_SESSION['KCFINDER']['uploadURL'] = '/' . trim($this->container->getParameter('kr_solutions_krcms.upload_dir'), '/');
     $_SESSION['KCFINDER']['uploadDir'] = $this->container->getParameter('kernel.root_dir') . '/../web/' . trim($this->container->getParameter('kr_solutions_krcms.upload_dir'), '/');
     $page = $this->getPageRepository()->getPageById($pageId);
     if (null === $page) {
         $request->getSession()->getFlashBag()->add('alert-danger', $this->getTranslator()->trans('file.page_not_exist', array('%page_id%' => $pageId), 'KRSolutionsKRCMSBundle'));
         return $this->redirect($this->generateUrl('kr_solutions_krcms_dashboard'));
     }
     if (false == $page->getPageType()->getHasFiles()) {
         $request->getSession()->getFlashBag()->add('alert-danger', $this->getTranslator()->trans('file.page_cannot_contain_files', array(), 'KRSolutionsKRCMSBundle'));
         return $this->redirect($this->generateUrl('kr_solutions_krcms_pages_index', array('siteId' => $page->getSite()->getId())));
     }
     $newFile = new File();
     $fileForm = $this->createForm('krcms_file', $newFile);
     $fileForm->handleRequest($request);
     if ($fileForm->isValid()) {
         $em = $this->getDoctrine()->getManager();
         $uriOrig = trim($newFile->getUri());
         $newFile->setUri(ltrim(ltrim($uriOrig, '/'), ltrim($uploadDir, '/')));
         $newFile->setPage($page);
         $em->persist($newFile);
         $em->flush();
         $request->getSession()->getFlashBag()->add('alert-success', $this->getTranslator()->trans('file.file_added', array(), 'KRSolutionsKRCMSBundle'));
         return $this->redirect($this->generateUrl('kr_solutions_krcms_files', array('pageId' => $pageId)));
     }
     return $this->render('KRSolutionsKRCMSBundle:File:index.html.twig', array('page' => $page, 'uploadDir' => $uploadDir, 'fileForm' => $fileForm->createView()));
 }
开发者ID:kr-solutions,项目名称:krcms-bundle,代码行数:39,代码来源:FileController.php

示例4: collect

 /**
  * {@inheritdoc}
  */
 public function collect(Request $request, Response $response, \Exception $exception = null)
 {
     $responseHeaders = $response->headers->all();
     $cookies = array();
     foreach ($response->headers->getCookies() as $cookie) {
         $cookies[] = $this->getCookieHeader($cookie->getName(), $cookie->getValue(), $cookie->getExpiresTime(), $cookie->getPath(), $cookie->getDomain(), $cookie->isSecure(), $cookie->isHttpOnly());
     }
     if (count($cookies) > 0) {
         $responseHeaders['Set-Cookie'] = $cookies;
     }
     $attributes = array();
     foreach ($request->attributes->all() as $key => $value) {
         if (is_object($value)) {
             $attributes[$key] = sprintf('Object(%s)', get_class($value));
             if (is_callable(array($value, '__toString'))) {
                 $attributes[$key] .= sprintf(' = %s', (string) $value);
             }
         } else {
             $attributes[$key] = $value;
         }
     }
     $content = null;
     try {
         $content = $request->getContent();
     } catch (\LogicException $e) {
         // the user already got the request content as a resource
         $content = false;
     }
     $this->data = array('format' => $request->getRequestFormat(), 'content' => $content, 'content_type' => $response->headers->get('Content-Type') ? $response->headers->get('Content-Type') : 'text/html', 'status_code' => $response->getStatusCode(), 'request_query' => $request->query->all(), 'request_request' => $request->request->all(), 'request_headers' => $request->headers->all(), 'request_server' => $request->server->all(), 'request_cookies' => $request->cookies->all(), 'request_attributes' => $attributes, 'response_headers' => $responseHeaders, 'session_attributes' => $request->hasSession() ? $request->getSession()->all() : array(), 'flashes' => $request->hasSession() ? $request->getSession()->getFlashBag()->peekAll() : array(), 'path_info' => $request->getPathInfo());
 }
开发者ID:krisldz,项目名称:Gekosale2,代码行数:33,代码来源:RequestDataCollector.php

示例5: indexAction

 public function indexAction(Request $request, $year, $month)
 {
     $em = $this->getDoctrine()->getManager();
     if ($year < 1970) {
         $year = date('Y');
     }
     if ($month < 1) {
         $month = date('m');
     }
     if ($request->getMethod() == 'POST') {
         $request->getSession()->set('filterCalendar', $request->get('id_user'));
     }
     if ($request->getSession()->get('filterCalendar')) {
         $selected_user = $request->getSession()->get('filterCalendar');
     } else {
         $selected_user = 0;
     }
     $weekStart = new \DateTime($year . '-' . $month . '-01');
     $weekStart = $weekStart->format('W');
     $calendar = $this->drawWeekCalendar($weekStart, $year, $selected_user);
     for ($i = $weekStart + 1; $i <= $weekStart + 6; $i++) {
         $calendar .= $this->drawWeekCalendar($i, $year, $selected_user);
     }
     $users = $em->getRepository('PointWebUserBundle:User')->findBy(array('enabled' => 1));
     return $this->render('PointWebCalendarBundle:Default:index.html.twig', array('calendar' => $calendar, 'year' => $year, 'nextYear' => $month == 12 ? $year + 1 : $year, 'lastYear' => $month == 1 ? $year - 1 : $year, 'month' => $month, 'nextMonth' => $month == 12 ? 1 : $month + 1, 'lastMonth' => $month == 1 ? 12 : $month - 1, 'users' => $users, 'selected_user' => $selected_user));
 }
开发者ID:Marquand,项目名称:Online-Mediashare-Prod,代码行数:26,代码来源:DefaultController.php

示例6: editAction

 /**
  * @Route("/familles/edition/{slug}")
  * @Template()
  */
 public function editAction($slug, Request $request)
 {
     if (!empty($slug)) {
         $session = $request->getSession();
         //0 valeur par defaut si vide
         $id_user = $session->get('user', 0);
         if ($id_user == 0) {
             $request->getSession()->getFlashBag()->add('error', 'OULAH ! Il s\'est passé un truc pas net O.o. Tu t\'es déco ?');
             return $this->redirect($this->generateUrl('corvee_taches_homepage', array()));
         }
         $em = $this->getDoctrine()->getManager();
         $famille = $em->getRepository('Corvees\\TachesBundle\\Entity\\Famille')->findOneBySlug($slug);
         if (!empty($famille)) {
             $form = $this->get('form.factory')->create(new FamilleEditType(), $famille);
             if ($form->handleRequest($request)->isValid()) {
                 $em = $this->getDoctrine()->getManager();
                 $em->persist($famille);
                 $em->flush();
                 $request->getSession()->getFlashBag()->add('notice', 'Famille bien enregistrée.');
                 return $this->redirect($this->generateUrl('familles', array()));
             }
             return array('form' => $form->createView(), 'famille' => $famille, 'route' => 'formulaire_famille_edit');
         }
     }
 }
开发者ID:pandorz,项目名称:gestionCorvees,代码行数:29,代码来源:FamillesController.php

示例7: listAction

 public function listAction(Request $request)
 {
     $cronjobs = $this->get('agentsib_crontab.manager')->getDatabaseCronjobs();
     if ($request->query->has('action') && $request->query->has('rand')) {
         $rand = $request->query->get('rand');
         $cronjob = $this->get('agentsib_crontab.manager')->getCronjobById($request->query->get('id'));
         if ($cronjob && !empty($rand) && $rand == $request->getSession()->get('agentsib_crontab_rand', '')) {
             switch ($request->query->get('action')) {
                 case 'enable':
                     $this->get('agentsib_crontab.manager')->enableCronjob($cronjob);
                     break;
                 case 'disable':
                     $this->get('agentsib_crontab.manager')->disableCronjob($cronjob);
                     break;
                 case 'immediately':
                     $this->get('agentsib_crontab.manager')->executeImmediatelyCronjob($cronjob);
                     break;
             }
         }
         return $this->redirect($this->generateUrl('agentsib_cronjob_tasks'));
     }
     $rand = mt_rand(10000000, 90000000);
     $request->getSession()->set('agentsib_crontab_rand', $rand);
     return $this->render('AgentSIBCrontabBundle::list.html.twig', array('cronjobs' => $cronjobs, 'rand' => $rand));
 }
开发者ID:agentsib,项目名称:crontab-bundle,代码行数:25,代码来源:CronjobController.php

示例8: indexAction

 /**
  * Index of the app
  *
  * @param Request $request
  * @return \Symfony\Component\HttpFoundation\Response
  */
 public function indexAction(Request $request)
 {
     $locale = $request->get('_locale');
     $request->setLocale($locale);
     $request->getSession()->set('_locale', $locale);
     $session = $request->getSession();
     $securityContext = $this->container->get('security.context');
     if ($securityContext->isGranted('ROLE_ADMIN')) {
         return $this->redirectToRoute('admin_homepage');
     } elseif ($securityContext->isGranted('ROLE_USER')) {
         return $this->redirectToRoute('user_homepage');
     } else {
         $authErrorKey = Security::AUTHENTICATION_ERROR;
         $lastUsernameKey = Security::LAST_USERNAME;
         // get the error if any (works with forward and redirect -- see below)
         if ($request->attributes->has($authErrorKey)) {
             $error = $request->attributes->get($authErrorKey);
         } elseif (null !== $session && $session->has($authErrorKey)) {
             $error = $session->get($authErrorKey);
             $session->remove($authErrorKey);
         } else {
             $error = null;
         }
         if (!$error instanceof AuthenticationException) {
             $error = null;
             // The value does not come from the security component.
         }
         // last username entered by the user
         $lastUsername = null === $session ? '' : $session->get($lastUsernameKey);
         $csrfToken = $this->get('security.csrf.token_manager')->getToken('authenticate')->getValue();
         return $this->render('BaseBundle:Default:index.html.twig', array('last_username' => $lastUsername, 'error' => $error, 'csrf_token' => $csrfToken));
     }
 }
开发者ID:smarquina,项目名称:misBeans,代码行数:39,代码来源:DefaultController.php

示例9: testAction

 /**
  * @Route("/helinorm-test/{number}" ,name="helinorm_test", options={"expose" = true})
  * @Template("VidalMainBundle:Helinorm:test.html.twig")
  */
 public function testAction(Request $request, $number)
 {
     $test = array(0 => array('question' => '<b>ВОПРОС №1 Из 6:</b>&nbsp;&nbsp;&nbsp;&nbsp;Были/есть ли у Ваших родственников серьезные случаи заболевания желудка (рак, язвенная болезнь)?', 'answers' => array(0 => 'Нет', 1 => 'Были/есть, но не такие серьезные', 2 => 'Были/есть')), 1 => array('question' => '<b>ВОПРОС №2 Из 6:</b>&nbsp;&nbsp;&nbsp;&nbsp;Как часто у Вас бывает изжога?', 'answers' => array(0 => 'Редко или никогда', 1 => 'Случается периодически как реакция на прием тяжелой или острой пищи', 2 => 'Мучаюсь каждый день')), 2 => array('question' => '<b>ВОПРОС №3 Из 6:</b>&nbsp;&nbsp;&nbsp;&nbsp;Часто ли у Вас бывает отрыжка после приема пищи?', 'answers' => array(0 => 'Не помню такого', 1 => 'Бывает, в зависимости от блюда, которое съел', 2 => 'Каждый раз после еды')), 3 => array('question' => '<b>ВОПРОС №4 Из 6:</b>&nbsp;&nbsp;&nbsp;&nbsp;Испытываете ли Вы боли и дискомфорт в желудке, которые проходят или, напротив, усиливаются после приема пищи?', 'answers' => array(0 => 'Никогда такого не было', 1 => 'Очень редко, но есть пища, на которую мой желудок так реагирует', 2 => 'Практически после каждого приема пищи')), 4 => array('question' => '<b>ВОПРОС №5 Из 6:</b>&nbsp;&nbsp;&nbsp;&nbsp;Не замечали ли Вы повышенного газоотделения (вздутия живота) после приема пищи?', 'answers' => array(0 => 'Только если выпью много газированной воды', 1 => 'Изредка, после приема острой или жирной пищи, после употребления алкоголя', 2 => 'Мучаюсь с этой проблемой постоянно')), 5 => array('question' => '<b>ВОПРОС №6 Из 6:</b>&nbsp;&nbsp;&nbsp;&nbsp;Как часто Вы принимаете обезболивающие средства (например, аспирин, диклофенак, ибупрофен)?', 'answers' => array(0 => 'Никогда', 1 => 'Иногда', 2 => 'Часто')));
     $testResult = array(0 => array('title' => 'Результат: вам не о чем беспокоиться, но забывать о профилактике не стоит!', 'text' => 'Скорее всего, у Вас не наблюдается каких-либо видимых проблем с желудочно-кишечным трактом. <a href="http://ad.adriver.ru/cgi-bin/click.cgi?sid=1&bt=2&ad=511031&pid=1919501&bid=3782870&bn=3782870&rnd=509224482" target="_blank">Правильный режим питания</a> и здоровый образ жизни, плановые профилактические визиты к врачу – залог здоровья в будущем.'), 1 => array('title' => 'Результат: состояние Вашего желудочно-кишечного тракта не идеально', 'text' => 'Проявите повышенную заботу о своем желудке. Возможно, Вам следует пересмотреть образ жизни и привычки питания. Желательно обратиться к врачу-гастроэнтерологу и пройти <a href="http://ad.adriver.ru/cgi-bin/click.cgi?sid=1&bt=2&ad=511031&pid=1919501&bid=3782871&bn=3782871&rnd=168803413" target="_blank">профилактическое обследование</a>.'), 2 => array('title' => 'Результат: Вам необходимо срочно обратиться к врачу.', 'text' => 'Срочно займитесь своим здоровьем. Обязательно посетите врача-гастроэнтеролога и пройдите обследование желудочно-кишечного тракта, сдайте тест на наличие <a href="http://ad.adriver.ru/cgi-bin/click.cgi?sid=1&bt=2&ad=511031&pid=1919501&bid=3782872&bn=3782872&rnd=1778476428" target="_blank">Хеликобактер пилори</a> и готовьтесь к тому, что образ жизни и режим питания придется менять.'));
     if ($request->getMethod() == 'POST') {
         $session = $request->getSession();
         $result = $session->get('heliresult');
         if ($result == null) {
             $result = 0;
         }
         $result += $request->request->get('answerNum');
         $session->set('heliresult', $result);
     } else {
         $session = $request->getSession();
         $result = $session->set('heliresult', null);
     }
     if ($number > 5) {
         if ($result <= 4) {
             $variable = 0;
         } elseif ($result <= 9) {
             $variable = 1;
         } else {
             $variable = 2;
         }
         return array('result' => $testResult[$variable], 'number' => $number + 1);
     } else {
         return array('question' => $test[$number], 'number' => $number + 1);
     }
 }
开发者ID:Evrika,项目名称:Vidal,代码行数:33,代码来源:HelinormController.php

示例10: filter

 /**
  * Checks if session was initialized and saves if current request is master
  * Runs on 'core.response' in test environment
  *
  * @param EventInterface $event
  * @param Response $response
  *
  * @return Response
  */
 public function filter(EventInterface $event, Response $response)
 {
     if (isset($this->request) && $this->master && null !== $this->request->getSession()) {
         $this->request->getSession()->save();
     }
     return $response;
 }
开发者ID:faridos,项目名称:ServerGroveLiveChat,代码行数:16,代码来源:SessionListener.php

示例11: loginAction

 public function loginAction(Request $request)
 {
     if (!$request->isMethod(Request::METHOD_POST)) {
         if ($this->getAuth()->hasAuthenticatedUser()) {
             return new RedirectResponse($request->getBasePath() . '/');
         }
         return new Response($this->getView()->render('Account::login/index'));
     }
     $loginParams = $request->request->all();
     $redirectUri = $request->server->get('HTTP_REFERER');
     $this->getAuth()->authenticate(Auth::METHOD_PASSWORD, ['identity' => $loginParams['identity'], 'credential' => $loginParams['credential']]);
     if (!$this->getAuth()->hasAuthenticatedUser()) {
         $request->getSession()->getFlashBag()->add('error', 'Username or Password doesn\'t match any user!');
         return new RedirectResponse($redirectUri);
     } else {
         $authenticatedUser = $this->getAuth()->getAuthenticatedUser();
         if (!$authenticatedUser->isActive()) {
             $this->getAuth()->deauthenticate();
             $request->getSession()->getFlashBag()->add('error', 'User account has not been verified!');
             return new RedirectResponse($redirectUri);
         }
         $continue = $request->query->get('continue');
         if (empty($continue)) {
             $admin = $this->getObjectManager()->getRepository('Jirro\\Bundle\\AccountBundle\\Domain\\Group')->findOneByCode('ADMIN');
             $continue = $request->getBasePath() . '/';
             if ($authenticatedUser->hasGroup($admin)) {
                 $continue .= 'admin';
             }
             return new RedirectResponse($continue);
         }
     }
 }
开发者ID:jirro,项目名称:jirro,代码行数:32,代码来源:AuthenticationController.php

示例12: indexAction

 /**
  * indexAction action.
  */
 public function indexAction(Request $request, $_format)
 {
     if (version_compare(Kernel::VERSION, '2.1.0-dev', '<')) {
         if (null !== ($session = $request->getSession())) {
             // keep current flashes for one more request
             $session->setFlashes($session->getFlashes());
         }
     } else {
         $session = $request->getSession();
         if (null !== $session && $session->getFlashBag() instanceof AutoExpireFlashBag) {
             // keep current flashes for one more request if using AutoExpireFlashBag
             $session->getFlashBag()->setAll($session->getFlashBag()->peekAll());
         }
     }
     $cache = new ConfigCache($this->cacheDir . '/fosJsRouting.json', $this->debug);
     if (!$cache->isFresh()) {
         $content = $this->serializer->serialize(new RoutesResponse($this->exposedRoutesExtractor->getBaseUrl(), $this->exposedRoutesExtractor->getRoutes()), 'json');
         $cache->write($content, $this->exposedRoutesExtractor->getResources());
     }
     $content = file_get_contents((string) $cache);
     if ($callback = $request->query->get('callback')) {
         $content = $callback . '(' . $content . ');';
     }
     return new Response($content, 200, array('Content-Type' => $request->getMimeType($_format)));
 }
开发者ID:raymondkadrige,项目名称:FOSJsRoutingBundle,代码行数:28,代码来源:Controller.php

示例13: onAuthenticationSuccess

 /**
  * This is called when an interactive authentication attempt succeeds. This
  * is called by authentication listeners inheriting from
  * AbstractAuthenticationListener.
  *
  * @param Request        $request
  * @param TokenInterface $token
  *
  * @return Response never null
  */
 public function onAuthenticationSuccess(Request $request, TokenInterface $token)
 {
     //TODO: setup facebookId
     if (method_exists($token, 'getResourceOwnerName') && $token->getResourceOwnerName() == 'facebook') {
         $facebookId = $token->getUserName();
         $user = $this->doctrine->getRepository('GameCoreBundle:User')->findOneByFacebookId($facebookId);
         if (!$user) {
             $request->getSession()->set('userAuthData', array('type' => 'facebook', 'id' => $facebookId));
             $request->getSession()->set('needRegister', true);
         } else {
             $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
             $this->security->setToken($token);
         }
     } else {
         $needRegister = $request->getSession()->get('needRegister');
         if ($needRegister === true) {
             $login = $token->getUserName();
             $user = $this->doctrine->getRepository('GameCoreBundle:User')->findOneByUsername($login);
             $userAuthData = $request->getSession()->get('userAuthData');
             if ($userAuthData['type'] == 'facebook') {
                 $user->setFacebookId($userAuthData['id']);
                 $this->doctrine->flush();
             }
             $request->getSession()->set('needRegister', false);
         }
     }
     $url = $this->router->generate('_welcome');
     return new RedirectResponse($url);
 }
开发者ID:nvvetal,项目名称:gnomek,代码行数:39,代码来源:LoginAuthHandler.php

示例14: loginAction

 /**
  * @Template()
  */
 public function loginAction(Request $request)
 {
     if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
         $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
     } else {
         $error = $request->getSession()->get(SecurityContext::AUTHENTICATION_ERROR);
     }
     return array('last_username' => $request->getSession()->get(SecurityContext::LAST_USERNAME), 'error' => $error);
     /*
     //$request = $this->getRequest();
     $session = $request->getSession();
     
     // get the login error if there is one
     if ($request->attributes->has(SecurityContext::AUTHENTICATION_ERROR)) {
         $error = $request->attributes->get(SecurityContext::AUTHENTICATION_ERROR);
     } else {
         $error = $session->get(SecurityContext::AUTHENTICATION_ERROR);
         $session->remove(SecurityContext::AUTHENTICATION_ERROR);
     }
     
     return $this->render('CoreBundle:Default:login.html.twig', array(
             // last username entered by the user
             'last_username' => $session->get(SecurityContext::LAST_USERNAME),
             'error'         => $error,
         ));
     */
 }
开发者ID:mishki-svami,项目名称:pa-core,代码行数:30,代码来源:DefaultController.php

示例15: passwordAction

 /**
  * @Route("/password", name="jc_user_password")
  */
 public function passwordAction(Request $request)
 {
     // If user has submit form => send new password by mail...
     if ($request->getMethod() == 'POST') {
         $mailAddress = $request->request->get('mail');
         if (!ValidateUtil::checkMail($mailAddress)) {
             $request->getSession()->getFlashBag()->add('popup-message', 'Le mail indiqué n\'est pas valide');
             return $this->render('jcUserBundle:FO:password.html.twig');
         }
         $entityManager = $this->getDoctrine()->getManager();
         $userList = $entityManager->getRepository('jcUserBundle:User')->findBy(array('mail' => $mailAddress));
         if (count($userList) == 0) {
             $request->getSession()->getFlashBag()->add('popup-message', 'Le mail indiqué est introuvable');
             return $this->render('jcUserBundle:FO:password.html.twig');
         }
         // Update password for user found + send mail
         $user = $userList[0];
         $accountMailService = $this->get('jc_user.account_mail');
         if ($accountMailService->sendNewAccountInformation($user->getId(), false)) {
             $request->getSession()->getFlashBag()->add('popup-message', 'Un mail contenant votre nouveau mot de passe vous a été envoyé');
         } else {
             $request->getSession()->getFlashBag()->add('popup-message', 'Erreur lors de l\'envoi du mail');
         }
     }
     return $this->render('jcUserBundle:FO:password.html.twig');
 }
开发者ID:jenasnic,项目名称:jc,代码行数:29,代码来源:AccountController.php


注:本文中的Symfony\Component\HttpFoundation\Request::getSession方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。