How to change the label appearing in symfony 2 form templates - php

I have this in template
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST" class="fos_user_registration_register">
{{ form_widget(form) }}
The form is appearing as
fos_user_registration_form_username --input box
fos_user_registration_form_email
fos_user_registration_form_plainPassword_first
fos_user_registration_form_plainPassword_second
But it want to have simple labels like Username , Email etc. How to do that

You can parse the individual form fields instead of the form as a whole.
{{ form_widget(form.fos_user_registration_form_username) }}
In this way, you can parse a single form element. Make sure to end with
{{ form_rest(form) }}
to output any not yet parsed fields (such as the csrf protection token).
using the above approach you can add your own labels to the fields.

FOSUserBundle uses the translator system. You need to as seen in the docs here:
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/1.2.0/Resources/doc/index.md
Add this:
# app/config/config.yml
framework:
translator: ~
To your config file (app/config/config.yml).
This will tell symfony to replace all the label values with the values found in the translator file (FOSUserBundle.en.yml). Then the form will always print "Username" instead of "fos_user_registration_form_username".

Related

Symfony 4: How to edit a given form control?

I can create a form view and even edit a submitted one.
But how can I do if I need for example to edit ONLY an user email.
Here's basically what I try:
{{ form_start(form) }}
{{ form_widget(form.id)}}
{{ form_widget(form._token) }}
{{ form_widget(form.email) }}
{{ form_widget(form.submit) }}
{{ form_end(form, {'render_rest': false}) }}
When I submit the form and dump the user after called $form->handleRequest($request), all the rest fields are reset to them default values except the ones I rendered in my twig view (id email).
So what the right way to achieve my goal?
I'm wondering what if I had differents FormType accordingly?
Dont know if this is the recommended way but it works!

Symfony 3 prevent full form rendering twig

I'm currently trying to only render specific parts of a form but for some reason, the whole form keeps getting rendered as you can see below I've used the form start and end and the whole form is still being rendered even though it should only render the start and end of the form tags.
{{ form_start(searchForm) }}
{{ form_end(searchForm) }}
Also whenever I use the code below all that happens is that the elements are being moved to the top of the form and the elements which shouldn't be rendered are rendered below.
{{ form_start(searchForm) }}
{{ form_widget(searchForm.title) }}
{{ form_widget(searchForm.title) }}
{{ form_end(searchForm) }}
As described in the doc, for don't render unrendered fields:
{{ form_end(form, {'render_rest': false}) }}
Hope this help

The CSRF token is invalid. Please try to resubmit the form

I'm getting this error message every time I try to submit the form:
The CSRF token is invalid. Please try to resubmit the form
My form code is this:
<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
<div class="form-group">
{{ form_label(form.email, 'Email', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.email, {'attr': {'class': 'col-md-2'}}) }}
{{ form_errors(form.email) }}
</div>
<div class="form-group">
{{ form_label(form.nickname, 'Nickname', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.nickname, {'attr':{'class': 'col-md-2'}}) }}
{{ form_errors(form.nickname, {'attr': {'class': 'col-md-3'}}) }}
</div>
<div class="form-group">
{{ form_label(form.password, 'password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.password, {'attr': {'class': 'col-md-2'}}) }}
{{ form_errors(form.password, {'attr': {'class': 'col-md-3'}}) }}
</div>
<div class="form-group">
{{ form_label(form.password_repeat, 'Repeat password', {'label_attr': {'class': 'col-md-1 control-label'}}) }}
{{ form_widget(form.password_repeat, {'attr':{'class': 'col-md-2'}}) }}
{{ form_errors(form.password_repeat, {'attr': {'class': 'col-md-3'}}) }}
</div>
<div class="form-group">
<div class="col-md-1 control-label">
<input type="submit" value="submit">
</div>
</div>
</form>
Any ideas?
You need to add the _token in your form i.e
{{ form_row(form._token) }}
As of now your form is missing the CSRF token field. If you use the twig form functions to render your form like form(form) this will automatically render the CSRF token field for you, but your code shows you are rendering your form with raw HTML like <form></form>, so you have to manually render the field.
Or, simply add {{ form_rest(form) }} before the closing tag of the form.
According to docs
This renders all fields that have not yet been rendered for the given
form. It's a good idea to always have this somewhere inside your form
as it'll render hidden fields for you and make any fields you forgot
to render more obvious (since it'll render the field for you).
form_rest(view, variables)
Also you can see this error message when your form has a lot of elements.
This option in php.ini cause of problem
; How many GET/POST/COOKIE input variables may be accepted
max_input_vars = 1000
Problem is that _token field misses PUT (GET) request, so you have to increase value.
Also, it concerns a big files. Increasing the
upload_max_filesize
option will solve problem.
This happens because forms by default contain CSRF protection, which is not necessary in some cases.
You can disable this CSRF protection in your form class in getDefaultOptions method like this:
// Other methods omitted
public function getDefaultOptions(array $options)
{
return array(
'csrf_protection' => false,
// Rest of options omitted
);
}
If you don't want to disable CSRF protection, then you need to render the CSRF protecion field in your form. It can be done by using {{ form_rest(form) }} in your view file, like this:
<form novalidate action="{{path('signup_index')}}" method="post" {{form_enctype(form)}} role="form" class="form-horizontal">
<!-- Code omitted -->
<div class="form-group">
<div class="col-md-1 control-label">
<input type="submit" value="submit">
</div>
</div>
{{ form_rest(form) }}
</form>
{{ form_rest(form) }} renders all fields which you haven't entered manually.
Before your </form> tag put:
{{ form_rest(form) }}
It will automatically insert other important (hidden) inputs.
I had this issue with a weird behavior: clearing the browser cache didn't fix it but clearing the cookies (that is, the PHP session ID cookie) did solve the issue.
This has to be done after you have checked all other answers, including verifying you do have the token in a hidden form input field.
In addition to others' suggestions you can get CSRF token errors if your session storage is not working.
In a recent case a colleague of mine changed 'session_prefix' to a value that had a space in it.
session_prefix: 'My Website'
This broke session storage, which in turn meant my form could not obtain the CSRF token from the session.
If you have converted your form from plain HTML to twig, be sure you didn't miss deleting a closing </form> tag. Silly mistake, but as I discovered it's a possible cause for this problem.
When I got this error, I couldn't figure it out at first. I'm using form_start() and form_end() to generate the form, so I shouldn't have to explicitly add the token with form_row(form._token), or use form_rest() to get it. It should have already been added automatically by form_end().
The problem was, the view I was working with was one that I had converted from plain HTML to twig, and I had missed deleting the closing </form> tag, so instead of :
{{ form_end(form) }}
I had:
</form>
{{ form_end(form) }}
That actually seems like something that might throw an error, but apparently it doesn't, so when form_end() outputs form_rest(), the form is already closed. The actual generated page source of the form was like this:
<form>
<!-- all my form fields... -->
</form>
<input type="hidden" id="item__token" name="item[_token]" value="SQAOs1xIAL8REI0evGMjOsatLbo6uDzqBjVFfyD0PE4" />
</form>
Obviously the solution is to delete the extra closing tag and maybe drink some more coffee.
I had this error recently. Turns out that my cookie settings were incorrect in config.yml. Adding the cookie_path and cookie_domain settings to framework.session fixed it.
I hade the same issue recently, and my case was something that's not mentioned here yet:
The problem was I was testing it on localhost domain. I'm not sure why exactly was this an issue, but it started to work after I added a host name alias for localhost into /etc/hosts like this:
127.0.0.1 foobar
There's probably something wrong with the session while using Apache and localhost as a domain. If anyone can elaborate in the comments I'd be happy to edit this answer to include more details.
In case you don't want to use form_row or form_rest and just want to access value of the _token in your twig template. Use the following:
<input type="hidden" name="form[_token]" value="{{ form._token.vars.value }}" />
In my case I got a trouble with the maxSize annotation in the entity, so I increased it from 2048 to 20048.
/**
* #Assert\File(
* maxSize = "20048k",
* mimeTypes = {"application/pdf", "application/x-pdf"},
* mimeTypesMessage = "Please upload a valid PDF"
* )
*/
private $file;
hope this answer helps!
I faced a similar issue. After ensuring the token field was actually rendered (see accepted answer) I checked my cookies.
There were 2(!) cookies for the domain in my Chrome browser, apparently because I was running the application on the same domain as another app, but with a different port (i.e. mydomain.com set the original cookie while the buggy app was running on mydomain.com:123)
Now apparently Chrome sent the wrong cookie so the CSRF protection was unable to link the token to the correct session.
Fix: clear all the cookies for the domain in question, make sure you don't run multiple applications on the same domain with differing ports.
I had the same error, but in my case the problem was that my application was using multiple first-level domains, while the cookie was using one. Removing cookie_domain: ".%domain%" from framework.session in the config.yml caused cookies to default to whatever domain the form was on, and that fixed the problem.
You need to remember that CSRF token is stored in the session, so this problem can also occur due to invalid session handling. If you're working on the localhost, check e.g. if session cookie domain is set correctly (in PHP it should be empty when on localhost).
This seems to be an issue when using bootstrap unless you are rendering the form by {{ form(form)}}. In addition, the issues seems to only occur on input type="hidden". If you inspect the page the with the form, you'll find that the hidden input is not part of the markup at all or it's being rendered but not submitted for some reason. As suggested above, adding {{form_rest(form)}} or wrapping the input like below should do the trick.
<div class="form-group">
<input type="hidden" name="_csrf_token" value="{{ csrf_token('authenticate') }}">
</div>

Save multiple instances of one entity with form submit in symfony2

Right now I'm rendering two forms ( one for company and one for it's tags ) and it looks like this:
<h3>Company</h3>
{{ form_start(form) }}
{{ form_row(form.name) }}
{{ form_row(form.city) }}
{{ form_row(form.street) }}
{{ form_row(form.postalcode) }}
{{ form_row(form.buildingnumber) }}
{{ form_row(form.vatid) }}
{{ form_row(form.tags) }}
<button id="test">Test</button>
{{ form_row(tags_form.title) }}
{{ form_row(form.save) }}
{{ form_end(form) }}
I want users to be able to add another input ( after clicking test button ) {{ form_row(form.tags) }} so they can add multiple tags with one form, but right now my tags form looks like this:
$builder
->add('title',null,array(
'label' => 'tag.title',
'required' => false
));
and I don't really know how to set this up. I tried with the simplest solution:
$('#test').on('click',function(e) {
e.preventDefault();
$('#fourcreate_portalbundle_companytags_title').clone().appendTo('form');
});
but that way submitting form creates entity only from the second input.
EDIT: I forgot to add - it has to be done with two forms, because first form contains list of currently available tags and the second form is to let users add their own.
You should not use two forms, but have a collection of tags_form in form.tags. The sample in the Cookbook is about adding tags.
The browser sends a "clobbered" form where two or more name attribute of two or more input elements have the same value. Hence, the back-end gets only the last value. I can not be more specific because I am not familiar with that part of Symfony.
If you wish to clone input elements, and have their values submitted correctly, you must at least modify the name attributes before submitting the form. Also, watch out for non-unique id attributes, as that violates the HTML (DOM?) standard.
e.g
var clone = $('input[id="original"]').clone();
clone.attr('name', clone.attr('name') + '1');

How can I use custom forms fields like table for symfony form

In Symfony docs they say to use this
<div>
{{ form_label(form.task) }}
{{ form_errors(form.task) }}
{{ form_widget(form.task) }}
</div>
But this generates the label element.
But I want to have table <td> instead of <label>
And also for the input textbox, I want to mention the size of text box. Where can I do that?
You have to define your form theme.
Probably, this tutorial is what you are looking for

Categories