Form Symfony 2.3 subscription - php

I am doing a form with Symfony 2.3 to suscribe to a newsletter.
The form is working good in is own template (newsletter.html.twig).
My controller action:
public function newsletterAction(Request $request)
{
$newsletter = new Newsletter();
$form = $this->createFormBuilder($newsletter)
->add('email', 'email')
->add('submit', 'submit')
->getForm();
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($newsletter);
$em->flush();
$request->getSession()->getFlashBag()->add('notice', 'Vous venez de vous enregistré à la Newsletter d\'Emoovio.');
}
return $this->render('MyBundle:Global:newsletter.html.twig', array(
'form' => $form->createView(),
));
}
My template where it's working (newsletter.html.twig) :
{{ form(form) }}
My template where it does not work (index.html.twig):
////
{% render (controller("EmooviofrontBundle:Global:newsletter")) %}
////
The form is display but it's not working. May be is miss something. Has anyone had the same problem and could explain me. Thank you.

I think that when you submit your form, the POST data arrives in the indexAction. This action does not validate your form and renders the normal page. While rendering it will call the Global:newsletterAction but just as a sub request in the GET method without form data.
You could try to apply an action to your formdata
$form = $this->createFormBuilder($newsletter, array(
'action' => $this->generateUrl('global_newsletter'),
'method' => 'POST',
))
->add('email', 'email')
->add('submit', 'submit')
->getForm();

Related

searchBar in nav Symfony 5.4

I'm a beginner ;)
I'm trying to have a searchBar form in a navbar located in base.twig.html, searching for the game just by it's name.
But i can't get any results when typing in the form in navbar. The functions in repo and controller are correct, I checked it with "dd".
This is my controller:
[Route('/search/SBresult', name: 'app_search')]
public function searchBar(Request $request, EntityManagerInterface $entityManager, string $Nazwa='Nazwa'):Response
{
$form = $this->createFormBuilder([])
->add('Nazwa', TextType::class, ['required' => false, 'label' => 'wpisz nazwę gry',
'label_attr'=> ['class'=>'text-white ps-3'], 'attr' => ['class'=>'form-control form-
control-lg']])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$Nazwa = $form->get('Nazwa')->getData();
//dd($Nazwa);
$Gry = $entityManager->getRepository(Gra::class)->findGra($Nazwa);
//dd($Gry);
return $this->render('search/SBresult.html.twig', ['Gry' => $Gry]);
//return $this->redirectToRoute('app_search', ['Gry' => $Gry], Response:: HTTP_SEE_OTHER);
}
return $this->render('search/searchBar.html.twig', ['form' => $form->createView()]);
}
I have a template search/SBresult.html.twig with a proper {% for Gry in Gry %}
And this is how I render the form in base.twig.html:
{{render (controller('App\\Controller\\SearchController::searchBar'))}}
I think that the problem lies in rendering the form in a navbar, because I've already made a searchform with many options to choose, exactly the same way, and it works. But this form is rendered in its own template, not in base.
What should I do to get the results from the searchBar in base.twig.html?

Symfony 3.4 - how are forms whose actions point to a different controller handled?

I want to process a form in a separate controller. While the Symfony docs show how to change a form's action and method, they don't show how the controller selected in $form->setAction() is actually supposed to handle the form. Is it present in Request? Do we make another Form object so we can check $form->isSubmitted() and $form->isValid()?
It's a pretty glaring omission.
Here is a quick example:
Controller for displaying the form
/**
* #route("/form", name="form_route")
*/
public function formAction()
{
$form = $this->createFormBuilder()
->setAction($this->generateUrl('task_route'))
->setMethod('POST')
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class)
->getForm();
return $this->render('form.html.twig', [
'form' => $form->createView(),
]);
}
Controller to handle submission
Is it present in Request?
Yes, the form data is in the request.
Do we make another Form object so we can check $form->isSubmitted() and $form->isValid()?
The form has to be recreated so that you can handle and validate the request.
/**
* #route("/task", name="task_route")
*/
public function postAction(Request $request)
{
$form = $this->createFormBuilder()
->add('task', TextType::class)
->add('dueDate', DateType::class)
->add('save', SubmitType::class)
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()){
$task = $form->getData();
/* ... */
}
//render task to view submission
return $this->render('task.html.twig', [
'task' => $task,
]);
}
This does have some duplicate code even when using entities and Symfony's Form Classes, which is why Symfony Docs recommends using the same controller for processing forms.

Are Symfony's forms not linkable?

i'm developing a light application with Symfony2 framework.
So, i need to create a form without link with an entity ; because the entity i want to fill is not fine to work with forms.
Any ideas ?
Thank's to everybody !
Yes Symfony supports forms that are not linked to Entities, the following snippet shows how you cant create a contact form that is not bound to an Entity.
public function indexAction(Request $request)
{
$form = $this->createFormBuilder()
->setAction($this->generateUrl('contact_route'))
->setMethod('POST')
->add('name', 'text')
->add('email', 'email')
->add('phone', 'text')
->add('message', 'textarea')
->add('submit', 'submit', array('label' => 'SUBMIT'))
->getForm()
;
$form->handleRequest($request);
if ($form->isValid()) {
$em = $this->getDoctrine()->getManager();
$message = \Swift_Message::newInstance()
->setSubject(''.$form->get('name')->getData() ." ". $form->get('phone')->getData())
->setFrom($form->get('email')->getData())
->setTo('email#ehost.com')
->setBody(''.$form->get('email')->getData().' '.$form->get('message')->getData());
$this->addFlash('notice','Thank you, we will contact you soon!');
$this->get('mailer')->send($message);
return $this->redirect($this->generateUrl('contact_route'));
}
return $this->render('BundleName:Contact:index.html.twig',array('form' => $form->createView(),));
}
this link is very useful to answer to the problem :
http://symfony.com/doc/current/book/forms.html#using-a-form-without-a-class
Thank's to everybody for your answers !

Symfony PUT method

I want send data via PUT method, my controller action:
public function updateTestAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$progress = $em->getRepository('CodeCatsPanelBundle:Progress')->find(5);
//$form = $this->createForm(new ProgressType(), $progress, array('method' => 'PUT'))->add('submit', 'submit');
$form = $this->createForm(new ProgressType(), $progress)->add('submit', 'submit');
$form->handleRequest($request);
return $this->render('CodeCatsPanelBundle:Progress:test.html.twig', [
'form' => $form->createView(),
'valid' => $form->isValid(),
'progress' => $progress,
'request' => $request
]);
}
the first one form works correct, but when I change method to PUT I receive validation error:
This form should not contain extra fields.
I know that Symfony2 use post and extra hidden field _method but how to valid data in this case?
just add a hidden input in your template like:
<form action='your route'>
<input type='hidden' name='_method' value='PUT'>
//do something.......
</form>
in your action:
public function updateTestAction(Request $request)
{
$em = $this->getDoctrine()->getManager();
$progress = $em->getRepository('CodeCatsPanelBundle:Progress')->find(5);
$form = $this->createForm(new ProgressType(), $progress)->add('submit', 'submit');
$form->handleRequest($request);
if ($form->isValid()){
//do something
}
return $this->render('CodeCatsPanelBundle:Progress:test.html.twig', [
'form' => $form->createView(),
'valid' => $form->isValid(),//you need this?
'progress' => $progress,
'request' => $request
]);
}
in your route config file:
yourRouteName:
path: /path
defaults: { _controller: yourBundle:XX:updateTest }
requirements:
_method: [PUT]
Most browsers do not support sending PUT and DELETE requests via the
method attribute in an HTML form.
Fortunately, Symfony provides you with a simple way of working around
this limitation.
Symfony 3
Enable http-method-override
In web/app.php:
Request::enableHttpMethodParameterOverride(); // add this line
Choose one of the following override:
In a Twig Template
{# app/Resources/views/default/new.html.twig #}
{{ form_start(form, {'action': path('target_route'), 'method': 'GET'}) }}
In a Form
form = $this->createForm(new TaskType(), $task, array(
'action' => $this->generateUrl('target_route'),
'method' => 'GET',
));
In a Controller / the lazy way
$form = $this->createFormBuilder($task)
->setAction($this->generateUrl('target_route'))
->setMethod('GET')
->add('task', 'text')
->add('dueDate', 'date')
->add('save', 'submit')
->getForm();
Post-Symfony 2.2
Same as above, just Step 2, Step 1 is done by default.
Pre-Symfony 2.2
Same as above, Step 1 and 2.
References
Faking the method with _method
Changing the action and methods in a form
Symfony configuration with http-method-override

Symfony 2 form choice field fails validation on POST (no data class)

Here is the form in controller action:
$form = $this->get('form.factory')->createNamedBuilder('meetings_form', 'form', $defaults)
->add('list','choice',array(
'choices' => array('1'=>'val1','2'=>'val2'),
'required' => false
))
->add('agency','text')
->add('name','text')
->add('phone','text')
->add('email','email')
->add('type','hidden')
->getForm();
Here is another action that handles POST
public function wsFormPostAction(Request $request)
{
if ('POST' == $request->getMethod()) {
$form = $this->get('form.factory')->createNamedBuilder('meetings_form', 'form')
->add('list', 'choice',array(
'choices' => array()
))
->add('agency', 'text')
->add('name', 'text')
->add('phone', 'text')
->add('email', 'email')
->add('type', 'hidden')
->getForm();
$form->bind($request);
if ($form->isValid()) {
$data = $form->getData();
} else {
$errors = $form->getErrorsAsString();
var_dump($errors);
}
}
}
And here is what I get:
list: ERROR: This value is not valid
agency: No errors
name: No errors
phone: No errors
email: No errors
type: No errors
There are no examples at all with choice fields without specifying data_class. It seems to be simple task, but I can't solve it. Why does it fails validation?
You pass 'choices' => array(). This means, that no choice is valid.
Your main problem is that there's different code for creating the same form. You should use FormType and register it, this way you can use form builder with string argument instead of form in any place you need it.
Another common pattern is to use the same controller action for showing and processing the form. If there are some errors in the form, you don't need to redirect, besides, after redirect you would not be able to insert the values that were typed in the previous page.

Categories