Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOS User Bundle Form Override

I am using FOS User Bundle + Symfony2.3. I want to override FOS User Bundle Form. Override and want to add login and registration Form in header file . For show in header I am using javascript.For example when I click tab-2 then open Registration form

One thing simply I am override this and this is working but When Registration Form call in other html then It is not working

I was doing this but this is So me error :

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

I do not know Why ?

My file is :

HeaderController.php

<?php
namespace XYZ\FrontBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use XYZ\UserBundle\Form\Type\RegistrationFormType;

class HeaderController extends Controller
{
    /**
     * @Route("/header", name="header")
     * @Template()
     */
    public function indexAction()
    {
        $registrationForm = $this->createForm(new RegistrationFormType());
        return array('registration_form'   => $registrationForm->createView());
    }
}
?>

Header(index.html.twig):-

{# Signup #}
<div id="tab-2" class="login_form">
<form action="{{ path('fos_user_registration_register') }}" {{ form_enctype(registration_form) }} method="POST" class="fos_user_registration_register">
<label><strong>Full Name</strong>
{{ form_widget(registration_form.username) }}
</label>
<label><strong>Email Address</strong>
{{ form_widget(registration_form.email) }}
</label>
<label><strong>Password</strong>
{{form_errors(registration_form.plainPassword)}}
{{ form_widget(registration_form.plainPassword.first, { 'attr':{'label': 'Password:'}  }) }}
</label>
<label><strong>Confirm Password</strong>
{{form_errors(registration_form.plainPassword)}}
{{ form_widget(registration_form.plainPassword.second, { 'attr':{ 'label': 'Retype Password:'} }) }}</label>
<input type="submit" class="submitBut" value="{{ 'registration.submit'|trans({}, 'FOSUserBundle') }}"/>
</form>
</div>

RegistrationFormType.php

<?php
namespace XYZ\UserBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;

class RegistrationFormType extends AbstractType
{
   public function buildForm(FormBuilderInterface $builder, array $options)
   {
    $builder
        ->add('username', null, array('label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
        ->add('email', 'email', array('label' => 'form.email', 'translation_domain' => 'FOSUserBundle'))
        ->add('plainPassword', 'repeated', array(
            'type' => 'password',
            'options' => array('translation_domain' => 'FOSUserBundle'),
            'first_options' => array('label' => 'form.password'),
            'second_options' => array('label' => 'form.password_confirmation'),
            'invalid_message' => 'fos_user.password.mismatch',
        ))
    ;
   }

   public function setDefaultOptions(OptionsResolverInterface $resolver)
   {
    $resolver->setDefaults(array(
        'data_class' => "XYZ\UserBundle\Entity\User"
    ));
   }


   public function getName()
   {
    return 'xyz_user_registration';
   }
}

Services.xml

<?xml version="1.0" ?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/dic/services http://symfony.com/schema/dic/services/services-1.0.xsd">

<services>
    <service id="xyz_user.registration.form.type" class="XYZ\UserBundle\Form\Type\RegistrationFormType">
        <tag name="form.type" alias="xyz_user_registration" />
        <argument>%fos_user.model.user.class%</argument>
    </service>
</services>
</container>

RegisterController.php

<?php
namespace XYZ\UserBundle\Controller;

use Symfony\Component\DependencyInjection\ContainerAware;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use FOS\UserBundle\Model\UserInterface;

/**
 * Controller managing the registration
 *
 */
class RegistrationController extends ContainerAware
{
  public function registerAction()
  {
    $form = $this->container->get('fos_user.registration.form');
    $formHandler = $this->container->get('fos_user.registration.form.handler');
    $confirmationEnabled = $this->container->getParameter('fos_user.registration.confirmation.enabled');

    $process = $formHandler->process($confirmationEnabled);
    if ($process) {
        $user = $form->getData();

        $authUser = false;
        if ($confirmationEnabled) {
            $this->container->get('session')->set('fos_user_send_confirmation_email/email', $user->getEmail());
            $route = 'fos_user_registration_check_email';
        } else {
            $authUser = true;
            $route = 'fos_user_registration_confirmed';
        }

        $this->setFlash('fos_user_success', 'registration.flash.user_created');
        $url = $this->container->get('router')->generate($route);
        $response = new RedirectResponse($url);

        if ($authUser) {
            $this->authenticateUser($user, $response);
        }

        return $response;
    }

    return $this->container->get('templating')->renderResponse('XYZUserBundle:Registration:register.html.'.$this->getEngine(), array(
        'form' => $form->createView(),
    ));
   }
}
?>

config.yml

fos_user:
    db_driver: orm
    firewall_name: main
    user_class: XYZ\UserBundle\Entity\User

    registration:
        form:
            type: xyz_user_registration
            name: xyz_user_registration_form
            validation_groups:  [Registration, Default]

Thanks!

like image 871
Kunwar Siddharth Singh Avatar asked Feb 15 '23 06:02

Kunwar Siddharth Singh


1 Answers

The form submission use an a CRSF token contained in an hidden input. you don't insert this input in your view. Try to insert this line before your submit button :

{{ form_rest(registration_form) }}
like image 181
Fabien Avatar answered Feb 23 '23 16:02

Fabien