Are Symfony's forms not linkable? - php

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 !

Related

Symfony Forms: Persisiting object with constructor to Databese

I am trying to persist an object of an entity to the database using symfony forms. The entity has an constructor therefore I am giving the object dummy data but I am not able to change this data with the forms. Does anyone have a solution how to create an object that requires a constructor?
public function new(Request $request)
{
$player = new Player("Dummy",0);
$form = $this->createFormBuilder($player)
->add('name', TextType::class)
->add('points', IntegerType::class)
->add('save', SubmitType::class, array('label' => 'Create Player'))
->getForm();
$form->handleRequest($request);
$data = $form->getData();
$name = $data->getName();
error_log($name);
$this->PlayerRepository->store($player);
return $this->render('default/new.html.twig', array(
'form' => $form->createView(),
));
}
$name has always the value "Dummy" no matter what I type in the form.
You save $player here:
$this->PlayerRepository->store($player);
But your actual player data from form is in $data, and this $data should be stored:
$this->PlayerRepository->store($data);
Okay, seems that I found the mistake.
I did not define the POST Route for the same controller building the view.
sorry for that :)

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.

Form Symfony 2.3 subscription

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();

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.

Call to undefined method isMethod on Symfony2

Here is my problem I'm following the symfony tutorial (Handling form submission) but I've the error "Call to undefined method Symfony\Component\HttpFoundation\Request::isMethod()" and I can't fix it.
I read in some website that isMethod was suppressed, but I can't find another way to perform my check.
Thanks.
use Symfony\Component\HttpFoundation\Request;
public function contactusAction(Request $request)
{
$contact = new ContactUs();
$form = $this->createFormBuilder($contact)
->add('nom', 'text')
->add('mail', 'email')
->add('sujet', 'choice', array('choices' => array('pt' => 'Problemes techniques', 'bi' => 'Boite a idees', 'd' => 'Divers')))
->add('msg', 'textarea')
->getForm();
if ($request->isMethod('post'))
{
$form->bind($request);
if ($form->isValid())
{
echo 'OK!';
//return $this->redirect($this->generateUrl('task_success'));
}
else
echo 'KO!!';
}
return $this->render('MyCoreBundle:Info:contactus.html.twig', array('form' => $form->createView()));
//return array();
}}
Update Symfony to the recent version or use
if ('POST' === $request->getMethod())
Also, be aware that the compared method string should be in uppercase.

Categories