Search code examples
phpsymfonysymfony-formsphp-5.3symfony-2.3

Get data from a form in symfony2


I have a problem with my search, probably I don't understand the principe. So I have a method witch show the products by category, and I added a search to this page for filter products by price. My method is :

 public function showCategoryAction($id, $page){
    $em = $this->getDoctrine()->getManager();
    $repositoryProduct = $em->getRepository('ShopDesktopBundle:Product');

    $aFilter = array();
    $form = $this->get('form.factory')->createNamedBuilder('search', 'form',  null,  array(
        'csrf_protection' => false,
            ))->setMethod('GET')
                ->add('minimPrice', 'text')
                ->add('maxPrice', 'text')
        ->getForm();
    $request = $this->getRequest();
    $form->handleRequest($request);
    $data = $form->getData();
    print_r($data);

    //Search products
    $aProducts          = $repositoryProduct->getProductsOrderByDateDesc($id,null,$aFilter);
    if (!$aProducts) {
        throw $this->createNotFoundException('Products not found.');
    }

    $category = $em->getRepository('ShopDesktopBundle:Category')->findOneById($id);
    if (!$category) {
        throw $this->createNotFoundException('Category not found.');
    }
    //Create pagination
    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $aProducts,
        $page,
        3
    );

    //Send data to view
    return $this->render('ShopDesktopBundle:Category:category.html.twig',array(
        'category'          => $category,
        'pagination'        => $pagination,
        'form' => $form->createView()
    ));
}

My view :

 <form action="{{ path('show_product_category',{ 'id':category.getId(), 'name':category.getCategoryLink() }) }}" method="get" {{ form_enctype(form) }}>
 {{ form_widget(form) }}
 <input type="submit" class="btn btn-primary marg-left-20" value="Search"/>
                    </form>

The problem is that my $var is empty. Help me please. What I'm doing wrong? Thx in advance


Solution

  • If I got you correct this may be the way to go. You need to handle form submission first, then you can get the data for your form fields.

    // You need your controller to pass the request
    $form->handleRequest($request);
    
    if ($form->isValid()) {
        //Get data from the form and query against the database
        //Render results to template
    } else {
      //Form is not submitted or not valid
    }
    

    http://symfony.com/doc/current/book/forms.html#handling-form-submissions

    Update: After many hours of chatting and finally some remote working with teamviewer. Turned out Nginx was misconfigured and removing query string parameters.

    That answer fixed our problem. https://stackoverflow.com/a/21484481/3399234

    location / {
       # try_files $uri $uri/ /index.php;
       try_files $uri $uri/ /index.php$is_args$args;
    }