Reputation: 1724
I am creating simple search form that will query and render data using Doctrine LIKE expression.I am confused how to get the parameter like this
$name = 'San Francisco China';
In the controller i created a simple form
public function searchAction(Request $request)
{
$data = array();
$form= $this->createFormBuilder($data)
->add('name_city', 'text', array(
'label' => 'Search Here',
'error_bubbling' => true,
))
->add('search', 'submit')
->getForm();
if ($request->isMethod('POST')) {
$form->handleRequest($request);
$data = $form->getData();
}
$name = $request->request->get('name_city');//this confused me
//$name = 'Beijing Angeles';//this will work
$em = $this->getDoctrine()->getManager();
$city = $em->getRepository('Bundle:City')->searchCity($name);
return $this->render('Bundle:City:list.html.twig', array(
'city' => $city,
'form' => $form->createView(),
));
}
In this case, the $name variable is passed to the searchCity method as the argument
public function searchCity($name)
{
return $this
->createQueryBuilder('c')
->select('c')
->where('c.name LIKE :name_city')
->setParameter('name_city', '%'.$name.'%')
// ->orderBy('v.dateCreated', 'DESC')
->getQuery()
->getResult()
;
}
//list.twig
{% extends '::base.html.twig' %}
{% block body %}
{{ form(form)}}
{% for city in city %}
{{ city }}
{% endfor %}
{% endblock %}
This will not work since all city name are displayed during page load. If i manually add a value to the $name, e.g $name = 'Beijing Washington', search works.Whats the correct way?
Upvotes: 0
Views: 57
Reputation: 20193
As for the setting the default name_city
, you could do this:
$data = array(
'name_city' => 'Beijing Angeles'
);
$form= $this->createFormBuilder($data)
->add('name_city', 'text', array(
'label' => 'Search Here',
'error_bubbling' => true,
))
->add('search', 'submit')
->getForm();
// The rest of your code
Then, get the city name like:
$form->handleRequest($request);
$data = $form->getData();
$name = $data['name_city'];
You might notice that I removed the POST
check. That's because search forms are traditionally set to method="get"
, because of history/bookmarks. So, in your example, you would never check for POST
but handlerRequest()
each and every time.
Hope this helps...
Feel free to correct me if I misunderstood the intention here ;)
Upvotes: 1