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.
Related
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
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...
I have an action that basically renders a form and I want it to be a new form if the ID is null and an edit form if the ID matches with the PK in the DB. Obviously my logic is wrong because a new form is rendering every single time. .
public function editGlobalFirewallFilter(Request $request, Entities\GlobalFirewallFilter $firewall_rule = null) {
n
// Check if we have a valid rule. If not create a new blank one and associate our account id
// if( ! $firewall_rule ) {
// $results = $this->getDoctrine()->getRepository('bundle:GlobalFirewallFilter');
// $rules = $results->findAll();
// $firewall_rule = new Entities\GlobalFirewallFilter();
// }
$firewall_rule = new Entities\GlobalFirewallFilter();
// Generate our form
$form = $this->createForm(new SAForms\GlobalFirewallRuleType(), $firewall_rule);
$form->handleRequest($request);
if($form->isValid()) {
// Save our firewall rule
$em = $this->getDoctrine()->getManager();
$em->persist($firewall_rule);
$em->flush();
return $this->redirect($this->generateUrl('_dashboard__global_firewall'));
}
return array(
'title' => $firewall_rule->getFirewallFilterId() ? 'Edit Rule' : 'New Rule',
'form' => $form->createView(),
);
}
You should use the form generator command to be oriented in the right way :
Generating a CRUD Controller Based on a Doctrine Entity
http://symfony.com/doc/current/bundles/SensioGeneratorBundle/commands/generate_doctrine_crud.html
use this command :
php app/console generate:doctrine:crud
I will generate the skeleton of you controller with all the standard actions as wanted, in your specifica case, updateAction, newAction, and editAction.
I am not quite sure why are there results and rules - you don't use them. I think this code should do the trick.
public function editGlobalFirewallFilter(Request $request, Entities\GlobalFirewallFilter $firewall_rule = null) {
// Check if we have a valid rule. If not create a new blank one and associate our account id
$firewall_rule = $firewall_rule ?: new Entities\GlobalFirewallFilter();
// Generate our form
$form = $this->createForm(new SAForms\GlobalFirewallRuleType(), $firewall_rule);
$form->handleRequest($request);
if($form->isValid()) {
// Save our firewall rule
$em = $this->getDoctrine()->getManager();
$em->persist($firewall_rule);
$em->flush();
return $this->redirect($this->generateUrl('_dashboard__global_firewall'));
}
return array(
'title' => $firewall_rule->getFirewallFilterId() ? 'Edit Rule' : 'New Rule',
'form' => $form->createView(),
);
}
P.S. Sadly I can't comment yet.. Can you provide controller actions where you use this function?
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()
];
}
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