Symfony 4 - how to add csrf token without building form? - forms

I am reading tutorial here
https://symfony.com/doc/current/form/csrf_protection.html
how to add csrf token. It says to use
form_end()
in the template. But this is not working, gives error:
Type error: Too few arguments to function
Symfony\Component\Form\FormRenderer::renderBlock(), 0 passed in
E:\projektai\php
projektai\htdocs\mokomieji\symfony_4_demo\var\cache\dev\twig\bb\bb2248f7be504240fcc2ab43dabf593090ebc4c897ce72b1a979082d62914b47.php
on line 48 and at least 2 expected
Here is answer which shows how to fix but it is only when you have form object built:
Symfony Type error: Too few arguments to function FormRenderer::renderBlock()
How to do this without having form object? Here is login from login documentation page:
{% if error %}
<div>{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}
<form action="{{ path('login') }}" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="_username" value="{{ last_username }}" />
<label for="password">Password:</label>
<input type="password" id="password" name="_password" />
<button type="submit">Login</button>
{{ form_end() }}

You can use the helper twig function csrf_token as described in the doc here, as example:
<input type="hidden" name="_csrf_token"
value="{{ csrf_token('authenticate') }}"
>
More help in this answer.
UPDATE:
Other strategy: pass from controller:
$tokenProvider = $this->container->get('security.csrf.token_manager');
$token = $tokenProvider->getToken('example')->getValue();
Hope this help

You can use {{ form_row(form._token) }} to generate the required CSRF token field to your form render in Symfony 3 (i'm currenlty use this method with Symfony 3.4).

{{ form_end() }} works only if you have something like this:
{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}
You can create custom token in your controller and then pass it to the view like this:
$csrf = $this->container->get('security.csrf.token_manager');
$token = $csrf->refreshToken('yourkey');
And then create hidden input in your twig with token:
<input type="hidden" name="_token" value="{{ token }}">

To get the right csrf_token you should create the FormView with $form->createView(), then use the token inside it:
<input type="hidden" name="_token" value="{{ form._token.vars.value }}">
All the other solutions rely on generating a static string that does not change, which violates the purpose of the csrf tokens.

Related

FormFacade class doesn't load Bootstrap classes in Laravel 5.5

I'm trying to load Bootstrap classes with FormFacade in a view but doesn't work.
I tried this steps: https://stackoverflow.com/a/46392838/3444714
But the Form class is generating fields without the effects of Bootstrap.
<div class="form-group">
{{ Form::label('testField', 'Test:') }}
{{ Form::text('testField', null, ['class' => 'formĀ­-control']) }}
<input type="text" id="testField" name="testField" class="form-control" />
</div>
Check my attachment, same code, but the field generated by FormFacade is wrong.
Thank you.

Getting form values of same form using twig

I'm adding a confirm details dialogue to a form before it gets submitted, using a bootstrap modal.
The form inputs look as follows:
<input type="email" ... name="email" id="email" value="{{ submitted.email }}"/>
I'd like to add a line of text to the modal body which reads something like:
"Send to foo#bar.com?"
I tried the these:
<p>Send to {{ form.email.get('value') }}</p>
<p>Send to {{ form.vars.value.email }}</p>
<p>Send to {{ submitted.email }}</p>
The modal is inside the form which has the input i.o.w:
<form method="post" ...>
...
<input type="email" ..../>
...
<button type="button" data-target="thisModal" data-toggle="modal"> Open Modal </button>
<div id="thisModal" class="modal"...>
...
<div class="modal-body>
<p>Send to {{ XXXXXXX }}</p>
</div>
<div class="modal-footer">
<button type="submit"> Send </button>
</div>
</div>
</form>
Using all 3 prior methods it was simply an empty string, is it possible to grab those values in this way, if so any guidance would be appreciated.
You can handle submitted form data in twig in this way:
{{ YOUR_FORM_VARIABLE.FORM_VARIABLE.vars.value }}
Do not forget to handle form request in your controller, after submitting data.
For sample:
// Some controller
public function indexAction(Request $request)
{
// supposing that FormType has only email field
$form = $this->createForm(FormType::class, null, array(
'action' => $this->generateUrl('homepage'),
));
$form->handleRequest($request);
return $this->render('Bundle:Homepage:layout.html.twig', array(
'form' => $form->createView()
));
}
And in template:
// Bundle:Homepage:layout.html.twig
{{ form(form) }}
<b>{{ dump(form.email.vars.value )}}</b>
The modal is being called via JavaScript so it doesn't hit PHP at the point wherein which the data needs to be transferred. Hence it cannot be done using twig, as the data is yet to be passed.

How to change Symfony2 FOSUser register form error message?

I have customized my register_content.html.twig like that
<form class="form-horizontal" action="{{ path('fos_user_registration_register') }}" {{ form_enctype(form) }} method="POST">
<div id="fos_user_registration_form">
<div class="form-group">
<div class="col-sm-10">
{{ form_widget(form.username, { 'attr': {'class': 'form-control', 'placeholder': 'Pick a username' } }) }}
{{ form_errors(form.username) }}
</div>
</div> ...
And now, when I'm getting an errors, those errors looks like that
fos_user.username.already_used
fos_user.email.already_used
fos_user.password.mismatch
I just want to change those messages, could anyone help me?
Once you enable the translator service, e.g.,
app\config\config.yml:
framework:
translator: { fallback: "%locale%" }
copy the appropriate FOSUserBundle.{locale}.yml from ...vendor/friendsofsymfony/userbundle/Resources/translations to ...app/Resources/translations. In the copied file, change the messages for
fos_user.username.already_used
fos_user.email.already_used
fos_user.password.mismatch

askbot-'askbot.deps.django_authopenid.forms.LoginForm object' has no attribute 'possword'

I have installed askbot app into my project. Now I login locally in askbot that is by providing "username & password". I see the following error:
'askbot.deps.django_authopenid.forms.LoginForm object' has no attribute 'possword'
Traceback tells that there is value="{{ login_form.possword.value() }}" line in the following file:
askbot/templates/authopenid/signin.html in block "content"
I didnot find that line at all.
Complete HTML
<div class="form-group">
<input class="required login" id="id_password"
maxlength="128" name="password" type="password"
{% if login_form.password.value() %}
value="{{ login_form.possword.value() }}"
{% endif %}
placeholder="{% trans %}Password{% endtrans %}
</div>
This is a bug. There was a typo in the variable name. It was fixed here.

Symfony2 - Form Validation Disabled?

Is there any way to disable form validation?
I have problem with datetime field.
I made in JQuery array with datetime data as follow,
$("[name='{{full_name}}[date][year]']").val(year);
$("[name='{{full_name}}[date][month]']").val(month);
$("[name='{{full_name}}[date][day]']").val(day);
$("[name='{{full_name}}[time][hour]']").val(hour);
$("[name='{{full_name}}[time][minute]']").val(minute);
But when I submit the form, I always get wrong value error messages for datetime field.
Does anyone already faced the same issue?
I made my own datetime type field because I wanted to make my own look of it. Firstly i made hidden inputs, and 2 visible inputs, like this:
<input type="date" value="{{ date_date }}" {{ block('widget_attr') }} class="form-control pull-left" style="width: 30%" placeholder="{{ 'date'|trans({},'app')|capitalize }}" name="TdateDate" />
<input type="time" value="{{ date_time }}" {{ block('widget_attr') }} class="form-control pull-left" style="width: 20%" placeholder="{{ 'time'|trans({},'app')|capitalize }}" name="TdateTime"/>
<input {{ block('widget_attr') }} name="{{full_name}}[date][year]" value="" class="hidden" />
<input {{ block('widget_attr') }} name="{{full_name}}[date][month]" value="" class="hidden"/>
<input {{ block('widget_attr') }} name="{{full_name}}[date][day]" value="" class="hidden" />
<input {{ block('widget_attr') }} name="{{full_name}}[time][hour]" value="" class="hidden"/>
<input {{ block('widget_attr') }} name="{{full_name}}[time][minute]" value="" class="hidden" />
Then with Javascript i put data from this two visible fields (date and time) to this 5 hidden inputs to make Datetime array type and i want to pass it to the form by name generated form my field in one variable... But form does not accept it.
From this 2 fields i bring data by JQuery script, like this:
var year = $("input[name='TdateDate']").val().substr(0, 4);
var month = $("input[name='TdateDate']").val().substr(5, 2);
var day = $("input[name='TdateDate']").val().substr(8, 2) ;
var hour = $("input[name='TdateTime']").val().substr(0, 2);
var minute = $("input[name='TdateTime']").val().substr(3, 2);
This part working fine, i think. I get datetime array passed to my form field but it just cant validate it...