Symfony 2 upload file simple form - php

Hello I want simple upload no database for now.
Inside of controller:
public function UploadAction(Request $request)
{
$form = $this->createFormBuilder( array('csrf_protection' => false))
->add('file', 'file')
->add('Send', 'submit')
->getForm();
if ($form->isValid()) {
$extension = $file->guessExtension();
if (!$extension) {
// extension cannot be guessed
$extension = 'bin';
}
$file->move('blah', rand(1, 99999).'.'.$extension);
}
return $this->render(
'FelekFosBundle:Plik:Upload.html.twig',
array(
'form' => $form->createView(),
)
);
}
Also I want to disable csrf_protection still code used seems not working.
Form is rendering well except csrf_protection. Still it's not preform any upload action. And I get errors.
csrf_message The CSRF token is invalid. Please try to resubmit the
form.

You have to call $form->handleRequest($request); before testing your form_validity.
The form isn't submited if you don't call handleRequest.
Options is on argument 2 of createFormBuilder method. Maybe
$form = $this->createFormBuilder( null, array('csrf_protection' => false))
could be better. Take a look here

Related

Symfony form submit and validate from another method

I have made a form created after an Ajax request (after the first form (Test1Type) is submitted)
public function indexAction(Request $request): Response
{
$form = $this->createForm(Test1Type::class);
$form->handleRequest($request);
if ($request->isXmlHttpRequest()) {
$form = $this->createForm(Test2Type::class);
return new Response($this->renderView('test/_results.html.twig', [
'form' => $form->createView(),
]));
}
return $this->render('test/index.html.twig', [
'form' => $form->createView(),
]);
}
Then I want to submit, validate and get the datas from this Test2Type in another method
public function confirmAction(Request $request): Response
{
dump($form->getData());
return $this->render('test/confirm.html.twig', [
]);
}
But I don't have acces to my form variable and I will not re-use $form = $this->createForm(Test2Type::class);...
I think this is possible but I really don't have any clues to made this work...
Do you have some ideas ?
It's not possible, you must create $form variable before using it for submittion and validation. To avoid duplicate code on create Test2Type form, you should redirect to confirmAction in indexAction after the form submitted and valid.
public function indexAction(Request $request)
{
$form = $this->createForm(Test1Type::class)->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->redirectToRoute('confirm.action.route_name');
}
return $this->render('test/index.html.twig', [
'form' => $form->createView(),
]);
}
public function confirmAction(Request $request)
{
$form = $this->createForm(Test2Type::class)->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
return $this->render('test/confirm.html.twig', [
'data' => $form->getData()
]);
}
return $this->render('test/_results.html.twig', [
'form' => $form->createView(),
]);
}
You should add another action in your controller for the ajax request with another route!!
This is better readable code and works better with the history button of your browser. (less cache problems) furthermore you can of course simply change the 'action' attribute of the HTML <form> element. Follow this link to read how: http://symfony.com/doc/current/form/action_method.html

Silex second form behind first form

What I want to do is quite simple. I have a first form. When this form is submitted, I have another form. When this second form is submitted, I want execute somes actions.
So here is my controller simplified:
$app->post('/path', function(Request $request) use ($app) {
$app['request'] = $request;
$token = $app['security.token_storage']->getToken();
if (null !== $token) {
$user = $token->getUser();
// First form
$form = $app['form.factory']->createBuilder(FormType::class)
->add('field_form1', TextType::class, [
'required' => true,
])
->getForm();
// Second form
$formcb = $app['form.factory']->createBuilder(FormType::class)
->add('field_form2', TextType::class, [
'required' => true,
])
->getForm();
// When second form is submitted
$formcb->handleRequest($request);
if($formcb->isSubmitted() && $formcb->isValid()) {
// isValid is never true
$data = $formcb->getData();
}
// When first form is submitted
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
switch ($data["paiementType"]) {
[...]
case 'mycase':
// Render of the second form
return $app['twig']->render('page2.twig', [
'form' => $formcb->createView(),
]);
default: break;
}
}
// Render of the first form
return $app['twig']->render('page1.twig', [
'form' => $form->createView(),
]);
}
})->bind('path');
But,
No problems for the first form, it works well.
The second form seems to have already been validated when it is render, because the fields errors message are display on the form.
When I submit the second form, I never enter in the if($formcb->isSubmitted() && $formcb->isValid()) { clause, because isValid is never true... However, the form is submitted...
So I don't know what is wrong, maybe it is not the good way to render a form behind another form...

Change Symfony form action once the request has been handled

I got a Symfony 2 form that has been created using createForm. Once the form has been validated I need to modify the action I initially set. Is this possible?
$formData = $this->loadData($id);
// Form builder
$form = $this->createForm(new ComposeForm(), $formData, [
'action' => $$this->generateUrl('defaultAction')
]);
// Processing form
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
$myVar = $form->get('myVar')->isClicked();
if ($myVar) {
// Can I change the form action here??
}
}
It's quite straight forward in a controller :
if ($myVar) {
$form->setAction($this->generateUrl('target_route'))
}
But I dont see the point of doing so.

Symfony Form - clear session variable only when I enter the form

I want to clear session variable only when I enter my symfony form first time. In this example session is delete even when form is not valid - how can I change this?
public function dodajNewAction(Request $request, Pacjent $pacjent)
{
unset($_SESSION['test']);
$wykbad = new Wykbadpoz($pacjent);
$wykbad->setRok(date('Y'));
$wykbad->setMiesiac(date('n')); //miesiac bez zera wiodacego
$form = $this->createForm('nfz_wykbadpoz_new', $wykbad);
$form->handleRequest($request);
return [
'form' => $form->createView()
];
}
In a Symfony project you should never use superglobals like $_SESSION ($_GET, $_POST, ...). You must use the Request object.
Like this:
public function dodajNewAction(Request $request, Pacjent $pacjent)
{
$wykbad = new Wykbadpoz($pacjent);
$wykbad->setRok(date('Y'));
$wykbad->setMiesiac(date('n')); //miesiac bez zera wiodacego
$form = $this->createForm('nfz_wykbadpoz_new', $wykbad);
$form->handleRequest($request);
$session = $request->getSession();
if ($form->isValid() && $session->has('test')) {
$session->remove('test');
}
return [
'form' => $form->createView()
];
}

silex passing form data to another page?

I'm really new to silex and symfony. This is my first foray into silex. I've got code that created my form in my app.php file from a little hacking and copying and pasting from documentation.
Now how do i pass this data to another page?
I would like to create a page that just dumps the post/get array to give me an idea how to pass around get/post variables.
Here's part of my app file:
<?php
/** /src/app.php */
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Register new application
*/
$app = new Application();
// skip to the form part ...
$app->match('/', function (Request $request) use ($app) {
// some default data for when the form is displayed the first time
$data = array(
'name' => 'Your name',
'email' => 'Your email',
);
$form = $app['form.factory']->createBuilder('form', $data)
->add('name')
->add('email')
->add('gender', 'choice', array(
'choices' => array(1 => 'male', 2 => 'female'),
'expanded' => true,
))
->getForm();
if ('POST' == $request->getMethod()) {
$form->bindRequest($request);
if ($form->isValid()) {
$data = $form->getData();
// do something with the data
// redirect somewhere
return $app->redirect('completed');
}
}
// display the form
return $app['twig']->render('index.html', array('form' => $form->createView()));
});
Would i then create a page like so?
<?php // app.php
$app->match('complete') use function ($app) {
// sorry psuedocode
foreach ($REQUEST as $key=> $var) {
echo "$key: $var";
}
}
You could try using a forward. http://silex.sensiolabs.org/doc/usage.html#fowards
// where params is the values from your POST
$subRequest = Request::create('/otherpage', 'GET', $params);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST);

Categories