簡體   English   中英

分頁,會話和控制器的動作-Symfony2

[英]Pagination, session and a controller's action - Symfony2

我有一個朋友列表,應在頁面中顯示3。 每個朋友都有一個類別,我也有一個下拉菜單,可以選擇僅查看來自所選類別的朋友。 它們還應該在頁面中顯示3。 過濾后的和未過濾的朋友的顯示方式是相同的,所以我不想在控制器中有兩個幾乎動作和兩個相同的模板,因此我嘗試在一個控制器的動作和模板中進行設置,但是有一個問題。 我無法對已過濾的朋友的第二頁及后續頁面進行分頁。 請幫助! :(問題是我使用了一個表單,當我單擊第二頁時,填充在表單中並綁定的變量變得不確定。這是代碼:

  1. 管制員的行動

     public function displayAction($page, Request $request) { $em = $this->getDoctrine()->getEntityManager(); $user = $this->get('security.context')->getToken()->getUser(); $cat = new Category(); $dd_form = $this->createForm(new ChooseCatType($user->getId()), $cat); if($request->get('_route')=='filter') { if($request->getMethod() == 'POST') { $dd_form->bindRequest($request); if($cat->getName() == null) { return $this->redirect($this->generateUrl('home_display')); } $filter = $cat->getName()->getId(); if ($dd_form->isValid()) { $all_friends = $em->getRepository('EMMyFriendsBundle:Friend') ->filterFriends($filter); $result = count($all_friends); $FR_PER_PAGE = 3; $pages = $result/$FR_PER_PAGE; $friends = $em->getRepository('EMMyFriendsBundle:Friend') ->getFilteredFriendsFromTo($filter, $FR_PER_PAGE, ($page-1)*$FR_PER_PAGE); $link = 'filter'; } } } else { $all_friends = $user->getFriends(); $result = count($all_friends); $FR_PER_PAGE = 3; $pages = $result/$FR_PER_PAGE; $friends = $em->getRepository('EMMyFriendsBundle:Friend') ->getFriendsFromTo($user->getId(), $FR_PER_PAGE, ($page-1)*$FR_PER_PAGE); $link = 'home_display'; } // Birthdays $birthdays = null; $now = new \\DateTime(); $now_day = $now->format('d'); $now_month = $now->format('m'); foreach ($all_friends as $fr) { if($fr->getBirthday() != null) { if($fr->getBirthday()->format('d') == $now_day && $fr->getBirthday()->format('m') == $now_month) { $birthdays[]=$fr; $fr->setYears(); } } } // Search $search = new Search(); $s_form = $this->createFormBuilder($search) ->add('words', 'text', array( 'label' => 'Search: ', 'error_bubbling' => true)) ->getForm(); // Renders the template return $this->render('EMMyFriendsBundle:Home:home.html.twig', array( 'name' => $name, 'friends' => $friends, 'user' => $user, 'birthdays' => $birthdays, 'pages' => $pages, 'page' => $page, 'link' => $link, 'dd_form' => $dd_form->createView(), 's_form' => $s_form->createView())); } 
  2. 模板

     {% if birthdays != null %} <div> <img class="birthday" src="http://www.clker.com/cliparts/1/d/a/6/11970917161615154558carlitos_Balloons.svg.med.png"> <div class="try"> This friends have birthday today: {% for bd in birthdays %} <p> <a href="{{ path('friend_id', {'id': bd.id}) }}">{{ bd.name }}</a> <span class="years"> ({{ bd.years }} years) </span> </p> {% endfor %} </div> </div> {% endif %} {% for fr in friends %} {# TODO: Fix where are shown #} {% if fr.getWebPath()!=null %} <a href="{{ path('friend_id', {'id': fr.id}) }}"> <img class="avatar" src="{{ fr.getWebPath }}"> </a> {% endif %} {% if loop.index is odd %} <p class="list1"> {% else %} <p class="list2"> {% endif %} <a class="friends" href="{{ path('friend_id', {'id': fr.id}) }}">{{ fr.name }}</a> </p> {% endfor %} {# TODO: Pagination #} {% if pages>1 %} <p> {% for i in 0..pages %} {% if page == loop.index %} <span class="pagination">{{ loop.index }}</span> {% else %} <span class="pagination"><a href="{{ path(link, {'page': loop.index}) }}">{{ loop.index }}</a></span> {% endif %} {% endfor %} </P> {% endif %} <p>Choose category:</p> <form class="search" action="{{ path('filter') }}" method="post" {{ form_enctype(s_form) }}> {{ form_widget(dd_form.name) }} {{ form_rest(dd_form) }} <input type="submit" value="Show friends" /> </form> 
  3. 知識庫

      FriendRepository類擴展EntityRepository\n {\n     公共函數getFriendsFromTo($ user,$ limit,$ offset)\n     {\n          返回$ this-> getEntityManager()\n             -> createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.user ='。$ user。'ORDER BY f.name ASC')\n              - > setMaxResults($限制)\n              - > setFirstResult($偏移)\n              - >的getResult();\n     }\n 公共功能filterFriends($ filter)\n     {\n         $ q = $ this-> createQueryBuilder('f'); 

    \n\n
      $q->select('f') ->where('f.category = :filter') ->setParameter('filter', $filter); return $q->getQuery()->getResult(); } public function getFilteredFriendsFromTo ($filter, $limit, $offset) { $q = $this->createQueryBuilder('f'); $q->select('f') ->where('f.category = :filter') ->setMaxResults($limit) ->setFirstResult($offset) ->setParameter('filter', $filter); return $q->getQuery()->getResult(); } } 

我嘗試了很多事情,但始終存在問題。 在這段代碼中,它表示$all_friends生日for循環中的變量$all_friends是的,沒有定義。 也許我必須將其存儲在會話中,然后嘗試了以下操作:

    $session = $this->getRequest()->getSession();

    $session->set('all_friends');

然后傳遞$friends=$session->get('all_friends'); 到for循環,但是它不起作用,並且變量$all_friends太大而無法存儲嗎?

任何想法將不勝感激! 感謝您的時間和精力!


編輯

當我在會話中使用

    $session = $this->getRequest()->getSession();

    $session->set('all_friends');

    $fri=$session->get('all_friends');

    foreach ($fri as $fr)
    { .... }

我得到的錯誤是

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\MyFriends\src\EM\MyFriendsBundle\Controller\HomeController.php line 100

並且

Warning: Missing argument 2 for Symfony\Component\HttpFoundation\Session::set(), called in C:\xampp\htdocs\MyFriends\src\EM\MyFriendsBundle\Controller\HomeController.php on line 71 and defined in C:\xampp\htdocs\MyFriends\app\cache\dev\classes.php line 148

當我不使用會話時,我得到

Notice: Undefined variable: all_friends in C:\\xampp\\htdocs\\MyFriends\\src\\EM\\MyFriendsBundle\\Controller\\HomeController.php line 100

當我選擇一個類別以顯示其中的朋友時,我單擊其第二頁。

PS錯誤中的行與我粘貼的代碼中的行並不一致,因為我跳過了動作,存儲庫和模板的某些部分,因為它們沒有參與此問題,並且可以正常工作。 如果有人願意,我可以發送給他或在此處更新所有代碼。

您沒有在會話中設置任何內容:

$session->set('all_friends');

您應該這樣做:

$session->set('all_friends', $data);

您還應該真正開始遵守Symfony2編碼標准。

當我嘗試閱讀您的代碼時,我的眼睛在融化。 您應該閱讀此內容 ,不要忘記創建表單類,而不是在控制器中創建表單。

編輯:如果$ data是來自Doctrine2查詢的結果,我建議您僅存儲entity identity class ,以便以后在需要時獲取它們。

EDIT2:以下代碼可以幫助您保存會話過濾器數據。 PS,別忘了添加缺少的use ....

/**
 * Set filters
 *
 * @param array  $filters Filters
 * @param string $type    Type
 */
public function setFilters($name, array $filters = array())
{
    foreach ($filters as $key => $value) {
        // Transform entities objects into a pair of class/id
        if (is_object($value)) {
            if ($value instanceof ArrayCollection) {
                if (count($value)) {
                    $filters[$key] = array(
                        'class' => get_class($value->first()),
                        'ids' => array()
                    );
                    foreach ($value as $v) {
                        $identifier = $this->getDoctrine()->getManager()->getUnitOfWork()->getEntityIdentifier($v);
                        $filters[$key]['ids'][] = $identifier['id'];
                    }
                } else {
                    unset($filters[$key]);
                }
            } elseif (!$value instanceof \DateTime) {
                $filters[$key] = array(
                    'class' => get_class($value),
                    'id'    => $this->getDoctrine()->getManager()->getUnitOfWork()->getEntityIdentifier($value)
                );
            }
        }
    }

    $this->getRequest()->getSession()->set(
        $name,
        $filters
    );
}

/**
 * Get Filters
 *
 * @param array $filters Filters
 * @param type  $type    Type
 *
 * @return array
 */
public function getFilters($name, array $filters = array())
{
    $filters = array_merge(
        $this->getRequest()->getSession()->get(
            $name,
            array()
        ),
        $filters
    );

    foreach ($filters as $key => $value) {
        // Get entities from pair of class/id
        if (is_array($value) && isset($value['class'])) {
            if (isset($value['id'])) {
                $filters[$key] = $this->getDoctrine()->getManager()->find($value['class'], $value['id']);
            } elseif (isset($value['ids'])) {
                $data = $this->getDoctrine()->getManager()->getRepository($value['class'])->findBy(array('id' => $value['ids']));
                $filters[$key] = new ArrayCollection($data);
            }
        }
    }

    return $filters;
}

EDIT3:為什么不使用KnpPaginatorBundle進行分頁?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM