How to handleRequest from html form in Symfony? - php

I have simple html form and controller to handle it. Notice I'm not using Symfony's forms in html.twig like {{form_start(form)}} .... So I want to handle from simple html forms in Controller.
My request body is contains below
+request: Symfony\Component\HttpFoundation\ParameterBag {#10
#parameters: array:2 [
"name" => "name"
"amount" => "name"
]
}
and in Controller.php I have $form
$defaultData = ['message' => 'Type your message here'];
$form = $this->createFormBuilder($defaultData)
->add('name')
->add('amount')
->getForm();
//here I can't handle the request;
$form->handleRequest($request);
// only 'message' is contain
dd($form->getData());
How to Use a Form without a Data Class From documentation I tried to handle request from html form without using $data = $request->request->get('data')

After all my tried to handle and asking in every Symfony forums, I founded this problem,
My mistake was just specify my requests parameters.
First I need to find out what is the name of my $form To solve this I dumped my $form that just created
dd($form);
[![enter image description here][1]][1]
After that my request should look like below
And after that I can handleRequest()!

Related

How do I catch form data in my controller using a class object and not the traditional getData() Method in symfony

I have created a search form in which I use to search my database to produce some result.
using the below in a my forms directory as a form class I generate the form.
$builder->add(
'startDate',
DateType::class,
[
'label' => 'start date',
'format' => 'yyyy-MM-dd',
'required' => true,
'constraints' => [
new Constraints\NotBlank(),
new Constraints\DateTime(),
],
]
);
in my controller I already have retrieved the data using the getData() method
$form = $this->createForm(testForm::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$start = date_format($form->get('start')->getData(), 'Y-m-d');
At the moment I want to get this data using a class object
e.g like this
$form = $this->createForm(testForm::class, $classobject);
$form->handleRequest($request);
where I would use the class object to retrieve the posted data from the form class "testForm"
how have I tried to solve this on my own?
I tried reading tutorials on this concept e.g as below
https://blog.martinhujer.cz/symfony-forms-with-request-objects/
note : this is a learning curve for me, I do not really grasp this concept
Please, constructive responses would be well appreciated.
Thanks
$form->getData() will return the object populated with the submited data. By default the Form Component returns an array, but if you pass an object as the second arg to createForm or set data_class option then you will get the object back.

How to handle bracket field arrays in Symfony REST API

I'm setting up a REST API using Symfony 3, and I can't get the array values send through a form, the latter being seen as not submitted in my controller.
The use case is to send an array of keywords through a POST form to a /media/keywords endpoint. Then, the endpoint would be able to get every single keyword and ac accordingly. There is no Doctrine entity to be involved here.
My action is as follow :
/**
* #Post(
* path = "/media/keywords",
* name = "app_media_keywords_update"
* )
* #View(StatusCode = 200)
* #RequestParam(name="keywords")
*/
public function keywordsAction(Request $request)
{
$form = $this->createFormBuilder()
->add('keywords', TextType::class)
->getForm();
$form->handleRequest($request);
echo "issub=".$form->isSubmitted()."<br>";
echo "isValid=".$form->isValid()."<br>";
die();
}
the output is as follow :
issub=
<br>isValid=
<br>
For testing purpose, I'm using Postman to simulate the POST submission as follows:
I don't understand why the form is seen as not submitted. Is something else needed ? Is my call to createFormBuilde() incorrect (in particular in respect with type, not being an array, only a TextType) ?
As you pass several items via keywords, you should use CollectionType:
$form = $this->createFormBuilder()
->add('keywords', CollectionType::class, [
'entry_type' => TextType::class
])
->getForm();
$form->handleRequest($request);
echo "issub=".$form->isSubmitted()."<br>";
echo "isValid=".$form->isValid()."<br>";
// also get form submit errors, for example:
if (!$form->isValid()) {
print_r($form->getErrors(true));
}
Form errors manual is here.

Handle form data by myself

I built a form with createFormBuilder
$form = $this->createFormBuilder($post)
->add("name", TextType::class, array("label"=>"Article Title"))
->add("content", TextareaType::class, array("label"=>"Article Content"))
->add("categories",
EntityType::class,
array(
"class" => Category::class,
"choice_label" => "name",
"multiple" => true,
"label" => "Article Category",
"required" => false
)
)
->add("attachments", TextType::class, array("required"=>false))
->add("submit", SubmitType::class, array("label"=>"Add new article"))
->getForm();
the "attachments" variable is an entity variable, I want to get a json string from the form and search the database by myself, like this:
$em = $this->getDoctrine()->getManager();
$attachmentsRepository = $em->getRepository(Attachment::class);
$attachments = $post->getAttachments();
$json = json_decode($attachments);
$dataSize = sizeof($json);
for ($i = 0; $i < $dataSize; $i ++) {
$attachment = $attachmentsRepository->find($json[$i]->getId());
$post->addAttachments($attachment);
}
$em->persist($post);
$em->flush();
However, there is the error hint said that:
Could not determine access type for property "attachments" in class
"App\Entity\Post".
I don't know how to solve this problem, if I add a #ORM\Column(type="string") in my Entity the json string will also be stored, I think this is not a good solution.
How do I modify my code?
First of all to get rid of the error you need to add mapped => false to the field options of your attachments field.
If the attachments fields is configured as a mapped field the form component will look for a setAttachments() method or a public property attachments in your Post Entity to set the value - which do not exist in your Post entity. That's why you get the error message:
Could not determine access type for property "attachments" in class "App\Entity\Post".
In order to transform the submitted JSON string to Attachment entities yourself you need a custom data transformer!
A good example how create and use a data transformer can be found in the documentation chapter How to Use Data Transformers.
A clean solution would involve the attachments field being a CollectionType of EntityType, sending the whole form as a JSON POST request and using i.e FOSRestBundle's fos_rest.decoder.jsontoform body listener to decode the JSON request to a form.
The documentation for FOSRestBundle's body listener support can be found here.

Symfony | Form | Mail

I've got problem with Symfony and I hope you would help me :)
I created a Form, which takes data from user (email, name, message) and then it saves data in database. Everything works fine but i also want to send e-mail with this data.
I want to use mail function mail(to,subject,message,headers,parameters);.
My Controller class looks like:
public function ContactFormAction(Request $request){
$post = new ContactForm();
$form = $this->createFormBuilder($post)
->setMethod('POST')
->add('email','text',['label' => 'Adres e-mail'])
->add('name','text', ['label' => 'Imię'])
->add('message','text', ['label' => 'Wiadomość'])
->add('save','submit', ['label' => 'Wyślij'])
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted()) {
$post = $form->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($post);
$em->flush();
$message=''; //thats my problem
mail('example#example.pl', 'Subject', $message);
return $this->redirectToRoute('onas');
}
return $this->render('default/aboutus.html.twig', ['form' => $form->createView()]);
}
My Problem is: how should the $message variable looks like if I want to get this data from user (from a form on my webpage).
Thanks a lot for all your answers :)
Not sure that I follow, but, you want to send plain text using user's input just do $message = $post->getMessage(); and pass it on to mail. Is that the issue?
E-mail are, by default, sent in text/plain encoding, so you won't be able to use HTML. Personally, I prefer to format it a little better than old-plain-text. To achieve this, I usually create a Twig template, pass the input data to it and render what I need. That template could contain some HTML which could enhance the email's visual look.

Validation of a form before submission

Using Symfony, version 2.3 and more recent, I want the user to click on a link to go to the edition page of an already existing entity and that the form which is displayed to be already validated, with each error associated to its corresponding field, i.e. I want
the form to be validated before the form is submitted.
I followed this entry of the cookbook :
$form = $this->container->get('form.factory')->create(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));
$form->submit($request->request->get($form->getName()));
if ($form->isValid()) {
...
}
But the form is not populated with the entity datas : all fields are empty. I tried to replace $request->request->get($form->getName()) with $myEntity, but it triggered an exception :
$myEntity cannot be used as an array in Symfony/Component/Form/Extension/Csrf/EventListener/CsrfValidationListener.php
Does anyone know a method to feed the submit method with properly formatted datas so I can achieve my goal ? Note : I don't want Javascript to be involved.
In place of:
$form->submit($request->request->get($form->getName()));
Try:
$form->submit(array(), false);
You need to bind the the request to the form in order to fill the form with the submitted values, by using: $form->bind($request);
Here is a detailed explanation of what your code should look like:
//Create the form (you can directly use the method createForm() in your controller, it's a shortcut to $this->get('form.factory')->create() )
$form = $this->createForm(new MyEntityFormType, $myEntity, array('validation_groups' => 'my_validation_group'));
// Perform validation if post has been submitted (i.e. detection of HTTP POST method)
if($request->isMethod('POST')){
// Bind the request to the form
$form->bind($request);
// Check if form is valid
if($form->isValid()){
// ... do your magic ...
}
}
// Generate your page with the form inside
return $this->render('YourBundle:yourview.html.twig', array('form' => $form->createView() ) );

Categories