Symfony2 - Requirement to provide a value value for an argument - php

The following exception is being returned when trying to use the method editAction() of a custom ProfileController herited from FOSuserbundle:
Controller "UserBundle\Controller\ProfileController::editAction()" requires that you provide a value for the "$id" argument (because there is no default value or because there is a non optional argument after this one).
UserBundle\Controller\ProfileController::editAction():
/**
* Edit the user
*/
public function editAction($id)
{
$user = $this
->getDoctrine()
->getManager()
->getRepository('UserBundle:User')
->find($id);
if (!is_object($user) || !($user instanceof UserInterface)) {
throw new AccessDeniedException('This user does not have access to this section.');
}
/** #var $dispatcher \Symfony\Component\EventDispatcher\EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** #var $formFactory \FOS\UserBundle\Form\Factory\FactoryInterface */
$form = $this->createForm(new RegistrationEditFormType(), $user);
$form->handleRequest($request);
if ($form->isValid()) {
/** #var $userManager \FOS\UserBundle\Model\UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
// Updating the user
$userManager->updateUser($user);
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('lld_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
$request->getSession()->getFlashBag()->add('info-edit', 'Your account has been updated!');
return $this->render('UserBundle:Profile:edit.html.twig', array(
'form' => $form->createView(),
'user' => $user
));
}
code snippet from admin.html.twig:
<tbody>
{% for user in users %}
<tr class="">
<td>{{ user.id }}</td>
<td>{{ user.firstName }}</td>
<td>{{ user.lastName }}</td>
<td>{{ user.amount }}</td>
<td>
{% if user.isAccountNonLocked %}
<span class="label label-success">Enabled</span>
{% else %}
<span class="label label-default">Disabled</span>
{% endif %}
</td>
<td>{{ user.date|date('m-d-Y H:i:s') }}</td>
<td>{{ user.updatedAt|date('m-d-Y H:i:s') }}</td>
<td></td>
<td>Delete Disable Enable Edit</td>
</tr>
{% endfor %}
</tbody>
The specific line being used:
<td>Delete Disable Enable Edit </td>
adminAction():
public function adminAction()
{
$user = $this->getUser();
if (!$this->container->get('security.context')->isGranted('IS_AUTHENTICATED_FULLY') || !$this->container->get('security.context')->isGranted('ROLE_ADMIN') || !$this->container->get('security.context')->isGranted('ROLE_MANUFACTURER')) {
return $this->redirect($this->generateUrl('fos_user_security_login'));
}
$userManager = $this->container->get('fos_user.user_manager');
$users = $userManager->findUsers();
return $this->render('UserBundle:Admin:admin.html.twig', array(
'users' => $users
));
}
public function deleteAction(Request $request, $id)
{
if (!$this->container->get('security.context')->isGranted('ROLE_ADMIN')) {
return $this->redirect($this->generateUrl('fos_user_security_login'));
}
$userManager = $this->container->get('fos_user.user_manager');
$user = $userManager->findUserBy(array('id' => $id));
if (null === $user) {
throw new NotFoundHttpException("User with id " . $id . " doesn't exist.");
}
$userManager->deleteUser($user);
$request->getSession()->getFlashBag()->add('info-delete', 'The user ' . strtoupper($user->getCompanyName()) . ' has been deleted successfully!');
return $this->redirect($this->generateUrl('admin'));
}
So, I got stuck and I'm not seeing where this issue is coming from since the argument is logically being retrieved from the line where the click is being made. Obviously the right action (the custom editAction()) is being called.
Is there something I'm missing? Any suggestions please? I tried the check out similar posts but none could help me.

The reason is that your are using native FOS routing, which does not have an id parameter at all.
<route id="fos_user_profile_show" path="/" methods="GET">
<default key="_controller">fos_user.profile.controller:showAction</default>
</route>
It's a Profile Edit page, which allows you to edit your own profile, so the id must be taken from a session.
If you are trying to provide some kind of CRUD functionality, you have to either switch to a ready-to-use datagrid / admin systems (e.g. SonataUserBundle) or write your custom routing and controller.

Related

Recover data session with relationship in Symfony with twig

I have a manyToOne relation of my entity ticket to my entity command. I store my tickets and my order in session. I can retrieve the command information by doing for example: {{app.request.session.get("command").Nom}}
But I can not view the ticket information. For example, if I want to get the ticket price 107 with twig?
session
Function of my service :
public function startCommande(Request $request)
{
$commande = new Commande();
$form = $this->form->create(CommandeBilletType::class, $commande);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()){
$data = $form->getData();
$this->session->set('commande', $data);
}
return $form;
}
public function coordonneesCommande(Request $request)
{
$commande= $this->session->get('commande');
$form = $this->form->create(CommandeType::class, $commande);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$this->price->tarifBillet($commande);
$response = new RedirectResponse('paiement');
$response->send();
}
return $form;
}
I tried {{app.request.session.get ("commande").Billet().Nom}}
{{app.request.session.get('Billet.nom')}}
...
You're trying to access a collection, you should iterate over it.
First set your "commande".
{% set commande = app.session.get('commande') %}
Now, you should be able to access the entity information and get your "billets" like this, (if i understand well you have a collection of billet):
{% for billet in commande.getBillet() %}
{{ billet.prix }}
{% endfor %}

How can i save and render array in symfony database?

i have an app for pizza ordering. i have entity orders. When i am submitting order i have problem, because i have checkboxes for ingredients and i am saving it as array.
Entity/Orders
/**
* #Assert\NotBlank(
* message="please select!")
* #Assert\NotNull(
* message="please select!")
* #ORM\Column(name="ingredients", type="array")
*
*/
protected $ingredients;
public static function getIngredientsOptions(){
return array('cheese','tomatoes','salami','onions','mushroom', 'bacon','ham','vegetables','peppers','olives');
}
DefaultController
private function buildForm($order) {
return $this->createFormBuilder($order)
->add('name','text',array('required'=>false))
->add('address','textarea',array('required'=>false))
->add('phone','number',array('required'=>false))
->add('email','text',array('required'=>false))
->add('box','choice',array(
'choices' => Orders::getBoxOptions()))
->add('ingredients','choice',array(
'choices' => Orders::getIngredientsOptions(),
'expanded' => true,
'multiple' => true))
->add('delivery','choice',array(
'choices' => Orders::getDeliveryOptions(),
'expanded' => true))
->add('save','submit')
->getForm();
}
/**
* #Route("/new", name="new_order")
* #Template()
*/
public function orderAction(Request $request)
{
$order = new Orders();
$form = $this->buildForm($order);
$form->handleRequest($request);
if ($form->isValid()) {
$order = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($order);
$em->flush();
return $this->forward('S1500238090PizzaBundle:Default:index');
}
return array('form' => $form->createView());
}
index.html.twig
<h3>Orders</h3>
<table border>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>E-Mail</th>
<th>Box</th>
<th>Ingredients</th>
<th>Delivery</th>
</tr>
{% for order in orders %}
<tr>
<td>{{order.id}}</td>
<td>{{order.name}}</td>
<td>{{order.address}}</td>
<td>{{order.phone}}</td>
<td>{{order.email}}</td>
<td>{{boxOptions[order.box]}}</td>
<td>{{ingredientsOptions[order.ingredients]}}</td>
<td>{{deliveryOptions[order.delivery]}}</td>
<td>
Edit
Delete
</td>
</tr>
{% endfor %}
</table>
New order
i don't know how to save ingredients array correctly and after that render it.
I found out that,I have to change index.html.twig ingredients tag with the following:
<td>{% for ingredient in order.ingredients %}
{{ingredient}}
{% endfor %}
</td>

Symfony 2: Multiple forms generated list of objects

I would like to generate page with list of users names and next to every user I would like to have button which would activate/deactivate this user.
I could of course create link with user ID and GET method in controller which would perform operation when link would be clicked. As far as I know it is not recommended though to do it this way due to security concerns. So instead of links to route which would perform operation I would like to have forms and buttons to submit request to PUT route which would change user status.
QUESTION: how to generate such forms (buttons) based on list of users returned by Doctrine?
Form code used to create form/button in user profile:
/**
* Creates a form to activate/deactivate a User entity by id.
*
* #param mixed $id The entity id
*
* #return \Symfony\Component\Form\Form The form
*/
private function createActivationDeactivationForm($id)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('user_activate', array('id' => $id)))
->setMethod('PUT')
->add('submit', 'submit', array('label' => 'Activate/Deactivate'))
->getForm()
;
}
Controller code used for user profile:
/**
* #Route("/user/{id}", name="user_show")
* #Method("GET")
* #Template()
*/
public function showUserAction($id)
{
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('TestUserBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find user');
}
$deleteForm = $this->createDeleteForm($id);
$activateForm = $this->createActivationDeactivationForm($id);
return array(
'user' => $user,
'delete_form' => $deleteForm->createView(),
'activate_form' => $activateForm->createView(),
);
}
Controller PUT method to perform operation from user profile:
/**
* Activate a user.
*
* #Route("/{id}", name="user_activate")
* #Method("PUT")
*/
public function activateAction(Request $request, $id)
{
$form = $this->createActivationDeactivationForm($id);
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$user = $em->getRepository('TestUserBundle:User')->find($id);
if (!$user) {
throw $this->createNotFoundException('Unable to find user');
}
$current_user_activity_flag = $user->getActive();
$user->setActive(abs($current_user_activity_flag-1));
$em->persist($user);
$em->flush();
}
return $this->redirect($this->getRequest()->headers->get('referer'));
}
Controller code to be used for users list:
/**
* #Route("/users", name="users_list")
* #Method("GET")
* #Template()
*/
public function listUsersAction()
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('TestUserBundle:User')->findExistingUsers();
//$deleteForm = $this->createDeleteForm($id);
//$activateForm = $this->createActivationDeactivationForm($id);
return array(
'users' => $users,
//'delete_form' => $deleteForm->createView(),
//'activate_form' => $activateForm->createView(),
);
}
I can not pass ID to form like I did for operation from profile cause for every user there is different ID and more of that Symfony generates only first form and ignores rest.
Any idea how to handle it? Or maybe my approach with form/buttons is incorrect and I should just use links instead?
I found solution which works though I am not sure about if it's compliant with best practices.
Instead of passing one form object in controller I generated an array of them with keys based on user ID. Than when looping through array in TWIG template I use user ID to refer form object created for current user.
Mentioned in question controller for user listing should than look like this:
/**
* #Route("/users", name="users_list")
* #Method("GET")
* #Template()
*/
public function listUsersAction()
{
$em = $this->getDoctrine()->getManager();
$users = $em->getRepository('PSUserBundle:User')->findExistingUsers();
$activate_forms = array();
$delete_forms = array();
foreach($users as $user)
{
$activate_forms[$user->getId()] = $this->createActivationDeactivationForm($user->getId())->createView();
$delete_forms[$user->getId()] = $this->createDeleteForm($user->getId())->createView();
}
return array(
'users' => $users,
'delete_forms' => $delete_forms,
'activate_forms' => $activate_forms,
);
}
... and in TWIG form within foreach should be refered like this:
{{ form_start(activate_forms[user.id], {'attr': {'novalidate': 'novalidate'}}) }}
{% if user.active %}
{{ form_widget(activate_forms[user.id].submit, {'attr': {'class': 'btn btn-xs btn-warning btn-block'}, 'label' : 'Deactivate'}) }}
{% else %}
{{ form_widget(activate_forms[user.id].submit, {'attr': {'class': 'btn btn-xs btn-success btn-block'}, 'label' : 'Activate'}) }}
{% endif %}
{{ form_end(activate_forms[user.id]) }}

Save Form from another Action

I have Two Action, GetAllPost and newComment
I have a page with many Post and each Post have commentForm
PostController
public function getPostAction () {
return array(
);
}
Twig
{% for post in app.user.posts %}
<p>{{ post.id }} - {{ post.description }} </p>
{{ render(controller("ADVCommentBundle:Comment:newComment" ,{ 'id': post.id,'redirect':'get_post' } )) }}
<hr>
{%endfor%}
CommentController
public function newCommentAction (Request $request, Post $post) {
$em = $this->getEm();
$comment = new Comment();
$form = $this->createForm(new CommentType(), $comment);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$em->beginTransaction();
$comment->setPost($post);
$em->persist($comment);
$em->flush();
$em->commit();
} catch (\Exception $e) {
$em->rollback();
throw $e;
}
}
return array(
'post' => $post,
'form' => $form->createView(),
);
}
TwifFormController
{{ form(form, {'action': path('new_comment',{'id': post.id})})}}
When I insert a new comment I have redirect to new_comment even if my value isn't valid.
How can I redirect to GeTAllPost and show the correct Error or the new Comment?
I tried to use
return $this->redirect($this->generateUrl('get_post',array('error',$form->getErrors())));
and 'error_bubbling' => true,, but each time request a get_post ( GetAllPost ) I do a new render of my Form and I don't see the errors
For Example i'd like to use newCommentAction in several scenario.
For example i GetAllPost for each post, but even in GetSpecificPost, where I Have A specific post, where I Can insert a new comment, but the save ( and the Action ) is the same.
Do I have create a Service ?
UPDATE
After Bonswouar's answer. This is my Code
PostController
/**
* #Route("/",name="get_posts")
* #Template()
*/
public function getPostsAction () {
$comment = new Comment();
return array(
'commentForms' => $this->createCreateForm($comment),
);
}
private function createCreateForm (Comment $entity) {
$em = $this->getEm();
$posts = $em->getRepository('ADVPostBundle:Post')->findAll();
$commentForms = array();
foreach ($posts as $post) {
$form = $this->createForm(new CommentType($post->getId()), $entity);
$commentForms[$post->getId()] = $form->createView();
}
return $commentForms;
}
/**
* #Method({"POST"})
* #Route("/new_comment/{id}",name="new_comment")
* #Template("#ADVPost/Post/getPosts.html.twig")
* #ParamConverter("post", class="ADVPostBundle:Post")
*/
public function newCommentAction (Request $request, Post $post) {
$em = $this->getEm();
$comment = new Comment();
//Sometimes I Have only One Form
$commentForms = $this->createCreateForm($comment);
$form = $this->createForm(new CommentType($post->getId()), $comment);
$form->handleRequest($request);
if ($form->isValid()) {
try {
$em->beginTransaction();
$comment->setPost($post);
$em->persist($comment);
$em->flush();
$em->commit();
} catch (\Exception $e) {
$em->rollback();
throw $e;
}
} else {
$commentForms[$post->getId()] = $form->createView();
}
return array(
'commentForms' => $commentForms,
);
}
And I Don't have any Render.
But, I want to re-use newCommentAction also in Single Post, and i Want to create Only one Form. I don't want use $commentForms = $this->createCreateForm($comment);, because i Want just one form,and I have to change template even. How can I do ?
If I'm not mistaking, your problem is that you're posting on new_comment, which is a "sub action".
You actually don't need this Twig render.
You could just generate all the forms you need in the main Action, with something like this :
foreach ($posts as $post) {
$form = $this->createForm(new CommentType($post->getId()), new Comment());
$form->handleRequest($request);
if ($form->isValid()) {
//...
// Edited : to "empty" the form if submitted & valid. Another option would be to redirect()
$form = $this->createForm(new CommentType($post->getId()), new Comment());
}
$commentForms[$post->getId()] = $form->createView();
}
return array(
'posts' => $posts,
'commentForms' => $commentForms,
);
Not forgetting to set a dynamic Name in your Form class :
class CommentType extends AbstractType
{
public function __construct($id) {
$this->postId = $id;
}
public function getName() {
return 'your_form_name'.$this->postId;
}
//...
}
And then just normally render your forms in your Twig loop. You should get the errors.
{% for post in app.user.posts %}
<p>{{ post.id }} - {{ post.description }} </p>
{{ form(commentForms[post.id]) }}
<hr>
{%endfor%}
If I didn't miss anything that should do the job.
UPDATE :
After seeing your update, this might be the controller you want (sorry if I didn't understand properly or if I did some mistakes):
/**
* #Route("/",name="get_posts")
* #Template()
*/
public function getPostsAction () {
$em = $this->getEm();
$posts = $em->getRepository('ADVPostBundle:Post')->findAll();
$commentForms = array();
foreach ($posts as $post) {
$commentForms[$post->getId()] = $this->createCommentForm($post);
}
return array(
'commentForms' => $commentForms
);
}
private function createCommentForm (Post $post, $request = null) {
$em = $this->getEm();
$form = $this->createForm(new CommentType($post->getId()), new Comment());
if ($request) {
$form->handleRequest($request);
if ($form->isValid()) {
try {
$em->beginTransaction();
$comment->setPost($post);
$em->persist($comment);
$em->flush();
$em->commit();
} catch (\Exception $e) {
$em->rollback();
throw $e;
}
$form = $this->createForm(new CommentType($post->getId()), new Comment());
}
}
return $form;
}
/**
* #Method({"POST"})
* #Route("/new_comment/{id}",name="new_comment")
* #Template("#ADVPost/Post/getPosts.html.twig")
* #ParamConverter("post", class="ADVPostBundle:Post")
*/
public function newCommentAction (Request $request, Post $post) {
return array(
'commentForm' => $this->createCommentForm($post, $request);
);
}
What about using a flash message to set your error messages? http://symfony.com/doc/current/components/http_foundation/sessions.html#flash-messages
EDIT: Modifying based on your comments. In your controller you could do this:
foreach ($form->getErrors() as $error) {
$this->addFlash('error', $post->getId().'|'.$error->getMessage());
}
or
$this->addFlash('error', $post->getId().'|'.(string) $form->getErrors(true, false));
What this will do is allow you to tie the error to the particular post you want, as you are passing it a string like 355|This value is already used. If you need to know the field you could add another delimiter for $error->getPropertyPath() in your flash message, or you could overwrite the error name in the entity itself.
Then in your controller you could parse out the flash messages, and add them to an array that your twig template would check:
$errors = array();
foreach ($this->get('session')->getFlashBag()->get('error', array()) as $error)
{
list($postId, $message) = explode('|', $error);
$errors[$postId][] = $message;
}
return array('errors' => $errors, ...anything else you send to the template)
Now your twig template can check for the existence of errors on that particular form:
{% for post in app.user.posts %}
{% if errors[post.id] is defined %}
<ul class="errors">
{% for error_message in errors[post.id] %}
<li>{{ error_message }}</li>
{% endfor %}
</ul>
{% endif %}
<p>{{ post.id }} - {{ post.description }} </p>
{{ render(controller("ADVCommentBundle:Comment:newComment" ,{ 'id': post.id,'redirect':'get_post' } )) }}
<hr>
{%endfor%}

Search form with multiple criteria , Symfony2

I'm trying to create a search form with multiple criteria but it doesn't work, and I think the controller does not receive the form because when I click Button Submit the page reloads only.
This is the Controller
/**
* #ParamConverter("agence", options={"mapping": {"agence_slug":"slug"}})
*/
public function indexAction(Agence $agence, Request $request)
{
$form = $this->createForm(new SearchTravelType());
$request = $this->getRequest();
$em = $this->getDoctrine()->getManager();
if ($request->getMethod() == 'POST')
{
$form->bind($request);
if ($form->isValid())
{
$criteria = $form->getData();
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListBy($criteria, $agence);
}
}
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->findByAgence($agence);
return $this->render('ProjectDashboardBundle:Travel:index.html.twig',
array(
'listTravels' => $listTravels,
'agence' => $agence,
'form' => $form->createView() ,
));
}
and this is the queryBuilder
class TravelRepository extends EntityRepository
{
public function getListBy($criteria, $agence)
{
$qb = $this->createQueryBuilder('t');
$qb = $this->whereAgence($qb, $agence);
$qb ->leftJoin('t.airport', 'a')
->addSelect('a');
foreach ($criteria as $field => $value) {
if (!$this->getClassMetadata()->hasField($field)) {
// Make sure we only use existing fields (avoid any injection)
continue;
}
$qb ->andWhere($qb->expr()->eq('t.'.$field, ':t_'.$field))
->setParameter('t_'.$field, $value);
}
return $qb->getQuery()->getResult();
}
public function whereAgence (\Doctrine\ORM\QueryBuilder $qb, $agence)
{
$qb->where('a.agence = :agence')
->setParameter('agence', $agence);
return $qb;
}
}
and this is the page twig and the form
<form class="form-horizontal" role="form" method="post" >
<td>{{ form_widget(form.id) }}</td>
<td class="center">-</td>
<td>{{ form_widget(form.title) }}</td>
<td>{{ form_widget(form.country) }}</td>
<td>{{ form_widget(form.destination) }}</td>
<td>{{ form_widget(form.airport) }}</td>
<td>{{ form_widget(form.departureDate) }}</td>
<td>{{ form_widget(form.returnDate) }}</td>
<td>{{ form_widget(form.price) }}</td>
<td>{{ form_widget(form.enabled) }}</td>
<td><span class="input-group-btn">
<button type="submit" class="btn btn-purple btn-sm">Search
<i class="icon-search icon-on-right bigger-110"></i></button>
</span>
</form>
I think the first problem is that form is not recovered in the controller, I tried with
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->find(1);
instead
getListBy($criteria, $agence)
to see what gives. the controller ignores the form and it goes directly to the following queries
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->findByAgence($agence);
You can remove $request = $this->getRequest(); from action as you are passing REquest object to this action;
You need to add action to your form,
like this:
$this->createForm(new SearchTravelType(), null, [
'action' => $this->generateUrl('ROUT')
]);
or like this:
<form class="form-horizontal" role="form" method="post" action="{{ path('ROUT') }}" >
EDIT:
We create a filter form with GET method (you should use POST method for inserting to DB, not for fetching results), disable CSRF protection. We create a controller action:
public function indexAction(Agence $agence, Request $request)
{
$form = $this->createForm(new SearchTravelType(), null, [
'action' => $this->generateUrl('ROUTE'),
'method' => 'GET'
]);
$form->handleRequest($request);
if ($form->isValid())
{
$em = $this->getDoctrine()->getManager();
$criteria = explode('&', $request->query->get($form->getName())); // I didn't test this line, you should check it..
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->getListBy($criteria, $agence);
// Terminate the request
return $this->render('ProjectDashboardBundle:Travel:index.html.twig',
array(
'listTravels' => $listTravels,
'agence' => $agence,
'form' => $form->createView() ,
));
}
$listTravels = $em->getRepository('ProjectTravelBundle:Travel')->findByAgence($agence);
return $this->render('ProjectDashboardBundle:Travel:index.html.twig',
array(
'listTravels' => $listTravels,
'agence' => $agence,
'form' => $form->createView() ,
));
}
You can try this bundle:
https://github.com/petkopara/PetkoparaMultiSearchBundle
Provides form or service for multi criteria search in Doctrine Entity.
In your case the form solution will solve your issue:
First in your form type just only add the MultiSearchType
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('search', MultiSearchType::class, array(
'class' => 'ProjectTravelBundle:Travel'));
}
Then in your Controller add the following code
public function indexAction(Request $request)
{
$search = $request->get('search');
$em = $this->getDoctrine()->getManager();
$queryBuilder = $em->getRepository('ProjectTravel:Travel')->createQueryBuilder('e');
$filterForm = $this->createForm('ProjectTravelBundle\Form\TravelType');
// Bind values from the request
$filterForm->handleRequest($request);
if ($filterForm->isValid()) {
// Build the query from the given form object
$queryBuilder = $this->get('petkopara_multi_search.builder')->searchForm($queryBuilder, $filterForm->get('search'));
}
..
}
At the last render your Travel form in your template
{{form_render(filter_form)}}

Categories