TanGio
TanGio

Reputation: 766

Retrieve data from a form with GET method using symfony2

I can't retrieve data from my form, I tried differents ways but no result. My repository :

public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('min_price', 'text', array('mapped' => false, 'label' => 'De la :', 'attr'=>
                                       array(
                                            'placeholder'=>'Pretul minim',
                                            'class'=>'form-control')))
            ->add('max_price', 'text', array('mapped' => false, 'label' => 'Pina la :' , 'attr'=>
                                        array(
                                            'placeholder'=>'Pretul maxim',
                                            'class'=>'form-control')))


            )
    ;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    parent::setDefaultOptions($resolver);
    $resolver->setDefaults(array(
        // avoid to pass the csrf token in the url (but it's not protected anymore)
        'csrf_protection' => false,
    ));
}

public function getName()
{
    return '';
}

My controller :

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

    $category = $em->getRepository('ShopDesktopBundle:Category')->findOneById($id);
    if (!$category) {
        throw $this->createNotFoundException('Category not found.');
    }
    $aFilter = array();

    $entity = new Product();
    $form = $this->createForm(new ProductType(), $entity,array(
        'action' => $this->generateUrl('show_product_category',array("id" => $id, "name" => $category->getCategoryLink(), "page" => $page )), //Your url to generate
        'method' => 'GET'
    ));
    $form->handleRequest($request);
    $aFilter['iMinPrice'] = $form["min_price"]->getData();
    $aFilter['iMaxPrice'] = $form["max_price"]->getData();
    print_r($aFilter);

    //Searchs products
    $aProducts          = $repositoryProduct->getProductsOrderByDateDesc($id,null,$aFilter);
    if (!$aProducts) {
        throw $this->createNotFoundException('Products 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) }}>
                        <div class="accordion-group">
                            <div class="accordion-heading">
                                <a class="accordion-toggle" data-toggle="collapse" data-parent="" href="#toggleOne">
                                    <em class="icon-minus icon-fixed-width"></em>Pret
                                </a>
                            </div>
                            <div id="toggleOne" class="accordion-body collapse in">
                                <div class="accordion-inner">
                                    {{ form_widget(form) }}
                                </div>
                            </div>
                        </div>
                        <input type="submit" class="btn btn-primary marg-left-20" value="Cautare"/>
                    </form>

The view :

show_product_category:
path:     /{id}/{name}/{page}
defaults: { _controller: ShopDesktopBundle:Category:showCategory, page: 1}
requirements:
    id:  \d+
    page: \d+
    _method:  GET|POST

So the problem is that I can't retrieve data from thi form. For all situations $aFilter is empty. If for example I put in the view in form POST method the filter is with data from form. My url look like this : ?min_price=10&max_price=50. Help me please. Thx in advance.Exist a solution??

Upvotes: 4

Views: 3433

Answers (1)

MikO
MikO

Reputation: 18741

I would not set the form method as GET, just do not specify a method and it will default to POST, which is the usual way to submit a form.

Then handle the form submission in your Controller when the method is POST - like this:

if ($request->isMethod('POST')) {
    $form->handleRequest($request);

    if ($form->isValid() {
        $aFilter['iMinPrice'] = $form->get('min_price')->getData();
        $aFilter['iMaxPrice'] = $form->get('max_price')->getData();
    }
}

More information on how to handle form submissions in Symfony2 here.


If you really need the form method to be GET, you should be able to get the query string parameters from the request:

$aFilter['iMinPrice'] = $request->query->get('min_price');
$aFilter['iMaxPrice'] = $request->query->get('max_price');

Upvotes: 2

Related Questions