Symfony2 fos login, register and forgot password in one view

寵の児 提交于 2019-12-05 13:29:28
Fabian Keller

I found a solution with which I am comfortable with for my current project. The advantages and disadvantages of the proposed solution upfront:

Advantages:

  • few LOC to implement
  • FOSUserBundle update proof (does not override the view scripts*)

Disadvantages:

  • performance overhead due to subrequests
  • only forms can be displayed, form submission (and subsequently error handling upon submission) will always go to the pages provided by FOSUserBundle
  • still feels like a quick-n-dirty fix, but better than other options

* only needs to override the layout.html.twig file


With that being said, here is what I have done:

  1. Render the form in your template
    Use embedded controllers to render the forms you need:

    <div>
        <h2>Login</h2>
        {{ render(controller('FOSUserBundle:Security:login', { embeddedForm: true})) }}
    </div>
    <div>
        <h2>Reset</h2>
        {{ render(controller('FOSUserBundle:Resetting:request', { embeddedForm: true})) }}
    </div>
    
  2. Override FOSUserBundle layout
    As I use the routes provided by the bundle, I had to override the FOSUserBundle layout template file to extend the standard layout of my application. As the overriden FOSUserBundle layout file extends the main applications layout file the layout would be repeated for each call {{ render ... }}. To prevent that, we need to dynamically disarm the extended layout file. Here is what the overriden layout file looks like:

    {# app/Resources/FOSUserBundle/views/layout.html.twig #}
    {% if app.request.get('embeddedForm') %}
        {% set layout = 'AcmeBundle::layout-content.html.twig' %}
    {% else %}
        {% set layout = 'AcmeBundle::layout.html.twig' %}
    {%  endif %}
    {% extends layout %}
    
    {% block content %}
        {% block fos_user_content %}{% endblock %}
    {% endblock %}
    
  3. Create the AcmeBundle::layout-content.html.twig file
    This layout should only render the content block of the FOSUserBundle view scripts and is such short and simple:

    {# src/Acme/DemoBundle/Resources/views/layout-content.html.twig #}
    {% block content %}{% endblock %}
    

Now the forms will render nicely with all dependencies (CSRF and so forth). Submitting the form will however take you to the FOSUserBundle actions.


Alternative solution:

  • This answer describes how to manually implement the forms and link them to the FOSUserBundle controller.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!