分页,会话和控制器的操作 - 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. 存储库

    class FriendRepository扩展EntityRepository{公共函数getFriendsFromTo($user,$limit,$offset){return$this->getEntityManager()->createQuery('SELECT f FROM MYFriendsBundle:Friend f WHERE f.user='.$user.'ORDER BY f.name ASC')->setMaxResults($limit)->setFirstResult($offset)->getResult();}公共函数filterFriends($filter){$q=$this->createQueryBuilder('f');
    
        $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();
    }
    }
    

我尝试了很多东西,但总是有问题。在这段代码中,它说生日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:xampphtdocsMyFriendssrcEMMyFriendsBundleControllerHomeController.php line 100

以及

Warning: Missing argument 2 for SymfonyComponentHttpFoundationSession::set(), called in C:xampphtdocsMyFriendssrcEMMyFriendsBundleControllerHomeController.php on line 71 and defined in C:xampphtdocsMyFriendsappcachedevclasses.php line 148

当我不使用会话时,我会得到

Notice: Undefined variable: all_friends in C:xampphtdocsMyFriendssrcEMMyFriendsBundleControllerHomeController.php line 100

当我从中选择一个类别来显示朋友时,我点击了它的第二个页面。

附言:错误中的行与我粘贴的代码中的行不一致,因为我跳过了操作、存储库和模板的某些部分,因为它们与这个问题无关,而且工作正常。如果有人愿意,我可以发送给他或在这里更新所有代码。

您在会话上没有设置任何内容:

$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进行分页?

相关内容

  • 没有找到相关文章

最新更新