symfony2 CSRF invalid - symfony

Okay, so today I updated my database with new information from our 'live' database... And since then I've been having issues on one of my forms. If you need any code let me know and i'll edit this and post the code needed...
I have a report form which has a date range field and a drop down for an agent department. When I first visit the page I see this at the beginning of the form:
The CSRF token is invalid. Please try to resubmit the form
So I go over to one of my other forms that has the same type of information, and check the _token out and this is what comes out:
<input type="hidden" id="ecs_crmbundle_TimeClockReportType__token" name="ecs_crmbundle_TimeClockReportType[_token]" value="87e358fbc4d6d3e83601216b907a02170f7bcd92" />
<input type="hidden" id="ecs_crmbundle_SimpleSalesReportType__token" name="ecs_crmbundle_SimpleSalesReportType[_token]" value="87e358fbc4d6d3e83601216b907a02170f7bcd92" />
The first one is the one that shows the error, and the SimpleSalesReport does not... Any idea why this is doing this or how I can fix it?
Thanks..

Are you by chance using $form->bindRequest() in the action which produces the CSRF error? I had this issue. You should not be binding the request for a new form. If you are posting the form to the same action, wrap the bindRequest in a conditional which checks if method is POST:
if ($this->getRequest()->getMethod() == 'POST') {
$form->bindRequest($this->getRequest());
if ($form->isValid()) {
...
}
}

There is no problem using {{ form_widget(form) }} to build your custom form.
All you have to do is add the _token like this:
{{ form_widget(form._token) }}

This error had me crazy for days!
Thanks krishna!
If in your form template you choose to not use the default form behavior {{ form_widget(form) }} you SHOULD put {{ form_rest(form) }}
Hope this could help anyone else!

Related

Display dynamically informations in a Symfony layout

I have a layout included in another one that display my menu. The labels of my menu items need to be dynamic (like the unread messages number of a mailbox). Then I did this :
My orders
(
{{ render(controller('MyController', {'etat':2})) }}
<span style="color:red">with {{ render(controller('MyController', {'etat':2})) }} in late</span>
)
I would like to display labels according to the number that return my controller. I don't know how to get it in a variable.
When rendering your template in your controller
return $this->render('twig_template_name.html.twig', array('variable_name' => $variable);
you pass a variable to the twig template in the array of options as I showed. Your code
{{ path('mypath',{'etat': '2' }) }}
prints a path defined in the routing.yml under the 'mypath' section and ends up adding a GET request variable to the link ('?etat=2'), if 'mypath' showed an absolute route 'www.website.com/yourpath',
{{ path('mypath',{'etat': '2' }) }} would produce 'www.website.com/yourpath?etat=2', which would send your controller for a route /yourpath/{etat} a variable etat with a value of 2 so all you need to do now is change 2 with an actual dynamic value which you receive from another controller.
I am not sure what etat is but lets say it's an article and it has it's id, you have a blog page with lots of articles and the controller that prints them all out sends an array of articles to the twig template, on your twig template you do something like:
{% foreach article in articles %}
{{ article.title }}
{{ article.story }}
read more
{% endforeach %}
And you end up something like:
Catchy Title
Awesome story about code without bugs and where deadlines depend on how creative and well designed and implemented the solutions are
[read more]
and you ofcourse click on "read more" and end up on the url ~/article/2 because the article had an id of 2, your controller for that url receives a variable id in the request, you do a $id = $_GET['id']; and grab the article from the repository and send it to the template.
Hopefully this answered your question, I am very tiered so forgive me if i was confusing which I surely was.

Symfony2: Set flash message after UNsuccessful login

I am using FOSUSerBundle and have successfully overwritten Controllers, Forms and Views.
But I cannot find the correct place to set a flash message after unsuccessful login.
I already tried modifying the checkAction() in SecurityController.php, but it doesnt work.
Where is the correct place to set my flash message?
Thank you very much in advance!
I solved the problem pretty straight-forward:
1.) have overwritten the SecurityController and edited the loginAction
2.) hooked into the case where the login process returns an not empty $error
// in case the login process returns an error...
if ($error) {
$error = $error->getMessage();
// ... add the desired flash message to display
$session->getFlashBag()->add('error', 'my error message here');
}
You dont need to overwrite the controller for it.
I overwrite the login.html.twig file and give the user the errors with the following line:
{% if error %}
<div class="alert alert-danger">{{ error.messageKey|trans(error.messageData, 'security') }}</div>
{% endif %}

Symfony2 : How to upload a file without Doctrine?

I use Symfony2.3. I have a form like this :
<form action="{{ path("member_update") }}" method="post" {{ form_enctype(form) }}>
{{ form_widget(form.pic) }}
...
{{ form_widget(form._token) }}
</form>
and i want to upload user pictures in a directory.Then i use this in controller :
$member , $form , $dm is defined...
if ($form->isValid()) {
// Handle profile picture upload process
$uploadDir=dirname($this->container->getParameter('kernel.root_dir')) . '/web/bundles/mybundle/myfiles';
$form['pic']->getData()->move($uploadDir,$member->getId());
// End of upload
$dm->persist($member);
$dm->flush();
return $this->redirect($this->generateUrl("member_profile"));
}
It must work,but i see this error:
Exception: Serialization of 'Symfony\Component\HttpFoundation\File\UploadedFile' is not allowed
1. in pathToMyProject...\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\DataCollector\DataCollector.php line 27
2. at serialize(.....
What's the problem??!
The problem solved! I change this line in MemberType :
$builder->add('pic','file');
to this :
$builder->add('pic','file', array('mapped'=>false));
My mistake was that i must explain the "pic" field is not mapped to the Entity(or Document in Mongo,as my project). Else Symfony kernel try to put the value of "pic" in a field of Entity. And i have not any field that hold a file! I upload the picture in a directory and store only path to the picture within the entity. When i changed this,the problem solved easily! :-)
So keep in mind to explain all things clearly to Symfony!

How to pass data from twig to Symfony2 controller using form

I would like to know if there is a method to pass some variables (text from textarea) from Twig to Symfony2 controller via form.
<form action="{{ path('admin_core_save') }}" method="post">
<div id="edit-template">
{% if template.getData() is defined %}
<textarea id="template">{{ template.getData() }}</textarea>
{% endif %}
</div>
<input type="submit" value="Save" />
</form>
When I press save button it is going to saveAction() method
public function saveAction(Request $request)
{
var_dump($request);
return new Response('abc');
}
but response does not contain any textarea text. Is there a way to get this there?
I know I can build form inside the controller and send it to Twig, but I would like to know if this way is possible.
you can access POST values through request object like:
$this->get('request')->request->get('name');
I'm sure you have to learn a bit about Symfony2 Form Component. You will find that symfony already has built-in system for rendering forms handling user data posted through them.
Answering your question. There is a Request object that provides you full access to all request data, including POST variables.
To access POST values use Request::get() method:
$request->get('variable_name');
To pass any data to the twig template, use TwigEngine::renderResponse
$this->container->get('templating')->renderResponse('AcmeDemoBundle:Demo:template.twig,html',
array(
'someVar' => 'some value'
)
);
This var will be avaliable in your template as:
{{ someVar }}

Extending existing Class in Symfony

I am new to symfony. I have created a registration form using the code:
$user = new Register();
$form = $this->createForm(new RegisterType(), $user);
In the RegisterType class i have 5 fields (for example).I store the values in database when the user registers with the system. Now I display the EDIT page using following code:
$user = $em->getRepository('MysiteUserBundle:Register')->find($id);
$form = $this->createForm(new RegisterType(), $user);
//edit.html.twig code
<form action="{{ path('MysiteUserBundle_register_update',{'id':user.id}) }}" method="post" {{ form_enctype(form) }} class="register">
{{ form_errors(form) }}
{{ form_row(form.firstname) }}
{{ form_row(form.lastname) }}
{{ form_row(form.username) }}
<p>
<input type="submit" value="Submit">
</p>
</form>
The problem with the EDIT code however is that it displays me all of the fields mentioned in RegisterType class.Is it possible to display only some fields. If yes how can this be achieved. Any help will be appreciated
It doesn't make sense to use the registration form type to edit a user, because registration happens once per user. Instead you could create another form type with only those fields you need when editing a user. One can extend the other to avoid duplication.
You could also:
Keep just one form type but add some fields conditionally — that is, only when the entity is new. You can get your entity in the form type as $options['data'] and check if its ID is not null or whatever.
Use form events.

Resources