2
votes

I have a list of friends which should be displayed 3 in a page. Each friend has a category and I also have a drop down menu to choose to view only the friends which are from the chosen category. They should also be display 3 in a page. The way in which filtered and not filtered friends are displayed is the same so I didn't want to have two almost actions in my controller and two identic templates, so I tried to make this in one controller's action and template, but there is a problem. I can't make the pagination for the second and following pages of the filtered friends. Pleae help! :( The problem is that I use a form and when I click on the second page, the variable which was filled in the form and binded, become undefined. Here is the code:

  1. Controller's action

    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. Template

    {% 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. Repository

     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();
    }
    }
    

I tried a lot of things, but there is always a problem. In this code it says that the variable $all_friends in the birthday for loop is not defined - and yes, it isn't. Maybe I have to store it in session and I tried this:

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

    $session->set('all_friends');

and then passing $friends=$session->get('all_friends'); to the for loop, but it doesn't work and isn't the variable $all_friends too big to store it?

Any ideas will be apreciated! Thank you for your time and effort!


EDIT

When I use the way with the session and

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

    $session->set('all_friends');

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

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

the error I get is

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

and also

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

When I don't use session I get

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

when I choose a category to show the friends from it, and I click its second page.

P.S. The lines from the errors don't corespond to the lines in the code I pasted, bacause I skipped some parts of the action, repository and template, because they don't have a part in this problem and they work correctly. If someone wishes, I can send him or update here all the code.

1
Can you please put the exect error message ? - Wearybands
can you post the error message so i can check where it occurs - Wearybands
Yes of course, I edited my question. - Faery
the line 100 is in your if condition where you get $all_friends or in else ? - Wearybands
The line 100 is foreach ($all_friends as $fr) It's some lines below //Birthdays - Faery

1 Answers

1
votes

You are setting nothing on session :

$session->set('all_friends');

You should be doing this instead:

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

You should really start respecting Symfony2 coding standards too.

My eyes are melting when I try to read your code. You should read this and don't forget to create form class instead of creating form in your controller.

EDIT: If your $data is a result from a Doctrine2 query, I suggest that you store only the entity id and the entity class in order to fetch them later when you need it.

EDIT2: Here's some code that might help you saving on session filters data. PS, don't forget to add the missing 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: Why you're not using KnpPaginatorBundle for pagination ?