Symfony Turbo Clear form after the success submit - php

I'm trying to clear my form after the form submit but unfortunately, it doesn't work
Here's my controller.
#[Route('/', name: 'homepage', methods: ['GET', 'POST'])]
public function index(Request $request, FooRepo $fooRepo): Response
{
$foo = new Foo();
$form = $this->createForm(FooType::class, $foo);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$fooRepo->save($foo, true);
if (TurboBundle::STREAM_FORMAT === $request->getPreferredFormat()) {
// If the request comes from Turbo, set the content type as text/vnd.turbo-stream.html and only send the HTML to update
$request->setRequestFormat(TurboBundle::STREAM_FORMAT);
return $this->render('shared/success.html.twig', ['status' => "Success!"]);
}
return $this->redirect($this->generateUrl("homepage"));
}
return $this->render('home/index.html.twig', [
controller_name' => 'HomeController',
'form' => $form
]);
}
So far, I tried the unset and redirect from this How can I clear form values after successful form submission but no success.
Here's my sample UI:
{{ form_start(form) }}
<input type="text" name=" {{ field_name(form.name) }} " placeholder="enter name"/>
<button type="submit">Save</button>
{{ form_end(form) }}
I'm using turbo that's why there's no page reload when I hit submit. There's no issue in saving but when the ajax call finished, the field doesn't clear after the submission. Any help?

Related

session flash message doesn't work when I add it in submitted form action with condition symfony

I have an edit page of my user object, so when the user have role admin and he is the connected user he doesn't have access to change his own role admin so I disabled the input of role when the user try to access the page to modify his own information, but before the form isSubmitted() I remove the disabled character from the input of role to access the content of the input in the action and check with a condition if this user try to change his password and display an error message
the edit action :
#[Route('/edit/{id}', name: 'app_user_edit', methods: ['GET', 'POST'])]
public function edit(Request $request, User $user, UserRepository $userRepository): Response
{
$session = $this->requestStack->getSession();
$session->set('key' ,$user->getId());
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
//dd($form->isValid());
if ($form->isSubmitted() && $form->isValid() ) {
if (in_array('ROLE_ADMIN',$user->getRoles()) && $user === $this->getUser()) {
if($user->getRoles() != ['ROLE_ADMIN','ROLE_USER']) {
$session = $request->getSession();
$session->getFlashBag()->add('error', 'You cannot change your role!');
} else{
$userRepository->add($user);
return $this->redirectToRoute('app_user_index', [], Response::HTTP_SEE_OTHER);
}}
}
return $this->renderForm('user/edit.html.twig', [
'user' => $user,
'form' => $form,
]);
}
the message in twig page
{% for message in app.flashes('error') %}
<div class="alert alert-success">
{{ message }}
</div>
{% endfor %}
The requestStack services is made to retrieve the request in a services. But you can't attach information in to it. If you wan't to add flashMessages to the request you can use the build in addFlash() method of your AbstractController.

Symfony3 Form builder setAction won't redirect to route

I have a form controlling the search bar in the websites navbar:
public function searchFormAction()
{
$form = $this->createFormBuilder()
->setAction($this->generateUrl('search'))
->setMethod('GET')
->add("value", TextType::class, array('label' => false))
->add("Search", SubmitType::class)
->getForm();
return $this->render('components/search-form.html.twig', [
"form" => $form->createView()
]);
}
As you can see, the form has a specific action path to this function:
/**
* #Route("/search", name="search")
*/
public function searchAction(Request $request)
{
return $this -> render ("post/post-search.html.twig", [
"value" => $request->query->get('value')
]);
}
For now this shouldn't do much more than just display the value on the page.
The problem is that the website fails to redirect when the form is used
So when I put foo in the search, and click submit the path looks like this:
localhost:8000/page?form%5Bvalue%5D=foo&form%5BSearch%5D=&form%5B_token%5D=PsouIRAy2QaQ8j2XO_uYrs7PcaR6jyjQN3W3_xRMdgw
Moreover if I go to localhost:8000/search and try to put anything into the search bar, no value is printed.
Here is how the form is rendered:
//search-form.html.twig
<form class="navbar-form navbar-left">
{{ form_start(form) }}
<div class="form-group">
{{ form_row(form.value) }}
</div>
{{ form_row(form.Search) }}
{{ form_end(form) }}
</form>
And placed in the base navbar:
//base.html.twig
//...
{{ render(controller(
'AppBundle:Form:searchForm'
)) }}
//...
Inspecting the element shows that the form tag has no action and method attributes
What could be the issue here and how can I fix it?
Fixed! Made a simple mistake in the twig file.
Placed the form start inside html form tags, that way the submit button would send to an empty form.

Symfony 2.8 : Rendering Controller (Form Errors Not Showing UP)

I have an issue trying to render a controller which returns a template with formView.
I understood about the sub-request, but I am having difficult time to show any kind of errors.
I think the problem is that after it sees the form is invalid it redirectsToRoute and it looses the POST Request.
If I don't say redirectTo it just renders the view.
base.html.twig
{{ render(controller('AppBundle:Utility:renderSignUpWizard'), {request: app.request}) }}
Utility Controller
/**
* #Route("/registration/wizard/", name="registration.wizard")
*/
public function renderSignUpWizardAction(Request $request)
{
/** #var $user User */
$user = $this->getUser();
$form = $this->createForm(SignUpWizardType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
// save changes to user
$this->persistAndSave($user);
// redirect to profile
return $this->redirectToRoute('profile');
}
else if($form->isSubmitted() && !$form->isValid())
{
return $this->redirectToRoute('home');
}
return $this->render('partials/signup-wizard.html.twig', array
(
'form' => $form->createView(),
));
}
If you could show the twig file where you put the form I could have given a clearer answer. Check the twig file you tell your controller to render and add the following:
Simple way to generate your form(doesn't include errors):
{{ form_start(form) }}
{{ form_widget(form) }
{{ form_end(form) }}
Add:
{{ form_errors(form) }}
if you want erors for a specific field:
{{ form_errors(form.name) }}

Attempt to update users table generates MethodNotAllowedHttpException, Laravel-4

UsersController:
public function update($id)
{
if( ! $this->user->isValid(Input::all()))
{
return Redirect::back()->withInput()->withErrors($this->user->errors);
}
$user = $this->user->find($id);
$user->save();
return Redirect::route('users.index');
}
Route:
Route::resource('users','UsersController');
Model:
protected $table = 'users'
edit.blade.php:
{{ Form::model($user, array('route'=>array('users.update','$user'=>'id'))) }}
I notice that this does NOT generate a "PUT" action. The page source:
<form method="POST" action="https://zocios.com/users/id" accept-charset="UTF-8"><input name="_token" type="hidden" value="...">
Hitting the Update User button gets me:
Exception \ MethodNotAllowedHttpException
Is the problem "$user->save();"? Something else I'm doing wrong? Thanks!
You need to specify the method:
{{ Form::model($user, array('method' => 'put', 'route'=>array('users.update','$user'=>'id'))) }}
There is no other method than GET and POST that is accepted (despite the specs), so the framework does the job of identyfying hidden input in your form _method to make it work.

"The CSRF token is invalid" error in symfony 2 even using form_rest(form) function

I've been trying to create a simple form in symfony but each time I try to submit I get the following error:
ERROR: The CSRF token is invalid. Please try to resubmit the form.
After surfing on the Internet and reducing the code to almost empty. I still get that error. Most of the people who I've seen asking for that solved the error using the following twig code
{{ form_rest(form) }}
The problem is that I'm using it, it's like when I bind the request it doesn't do it correctly. I don't know what else can I do.
This is my small twig template:
<div><h2>Insert new activity</h2></div>
<div>
<form id="new-activity" action="{{ path('create') }}" method="post" {{ form_enctype(form) }}>
{{ form_rest(form) }}
<p>
<button type="submit">Submit</button>
</p>
</form>
</div>
As you can see it is pretty small code. This is my form render code:
/**
* Displays a form to create a new Activity entity.
*
* #Route("/new", name="sucr_new")
* #Template()
*/
public function newAction() {
$initialConfig = new SucrConfiguration();
$finalConfig = new SucrConfiguration();
$activity = new SucrActivity();
$data = array("activity" =>$activity,
"initialConfig" => $initialConfig,
"finalConfig" => $finalConfig);
$form = $this->createForm(new ActivityType(), $data);
return array(
'data' => $data,
'form' => $form->createView()
);
}
And this is the code that should handle the submition:
/**
* Displays a form to create a new Activity entity.
*
* #Route("/create", name="create")
* #Method("post")
* #Template("EusocSucrBundle:Sucr:new.html.twig")
*/
public function createAction() {
$initialConfig = new SucrConfiguration();
$finalConfig = new SucrConfiguration();
$activity = new SucrActivity();
$data = array("activity" =>$activity,
"initialConfig" => $initialConfig,
"finalConfig" => $finalConfig);
$form = $this->createForm(new ActivityType(), $data);
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
if ($form->isValid()) {
return $this->redirect($this->generateUrl('sucr_show', array('id' => 1)));
}
var_dump($form->getErrorsAsString());
}
return array(
'data' => $data,
'form' => $form->createView()
);
}
Also note that I can see the hidden token in my browser.
Any ideas?

Categories