分页,会话和控制器的动作 - Symfony2

时间:2012-09-12 13:35:52

标签: php symfony doctrine-orm

我有一个朋友列表,应该在页面中显示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 extends EntityRepository
    {
        public function getFriendsFromTo ($user, $limit, $offset)
        {
             return $this->getEntityManager()
                ->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.user='.$user. 'ORDER BY f.name ASC')
                ->setMaxResults($limit)
                ->setFirstResult($offset)
                ->getResult();
        }
    public function 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();
    }
    }
    
  4. 我尝试了很多东西,但总有一个问题。在此代码中,它表示生日循环中的变量$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

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

    P.S。错误中的行与我粘贴的代码中的行没有对应,因为我跳过了操作,存储库和模板的某些部分,因为它们没有参与此问题并且它们正常工作。如果有人愿意,我可以发送给他或在这里更新所有代码。

1 个答案:

答案 0 :(得分:1)

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

$session->set('all_friends');

你应该这样做:

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

你也应该开始尊重Symfony2编码标准。

当我尝试阅读你的代码时,我的眼睛正在融化。您应该阅读this并且不要忘记创建表单类而不是在控制器中创建表单。

编辑:如果您的$数据是来自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进行分页?