Symfony 4:
Sonata User : Override registration form
There are many tutorials about overriding registration form .
But , if you have both FOSUser and SonataAdmin installed, the task is not as easy as you think because you don’t know which entity is managed by the framework .
Scrolling directory structure , you find many classes has the name of User.php
So , you should understand with is the final entity to be added to the database after registration .
FOSUser is the bundle which provide the entity User management .
And this entity is the one which is under SonataUser.
#config/packages/fos_user.yamlfos_user: #...
user_class: Sonata/UserBundle/Entity/User
The class at the top is our beloved . The following architecture is done to get both FOSUser and Sonata User attributes .
Now ,If you understand the final entity, you can execute the following steps easily :
- Create a folder “Form” under src
- Create a new Form : RegistrationType
<?php
namespace App\Form;use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;class RegistrationType extends AbstractType{public function buildForm(FormBuilderInterface $builder, array $options){
$builder
->add('website')
->add('dateOfBirth');
}public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}public function getBlockPrefix()
{
return 'app_user_registration';
}}
3. Add to buildForm action attributes you wish to add to registration form
In this example , I added website and dateOfBirth
warning : be careful of the spelling. It’s wiser to copy the attribute name from its declaration .
4. Tell FOSUser that the new form is no longer the default one . So add the new path under registration.form:
#config/packages/fos_user.yamlfos_user:
registration:
#..
form:
type: App\Form\RegistrationType #...
user_class: Sonata/UserBundle/Entity/User
5. Now , browse 127.0.0.1:8000/register
If you want to learn more , please check these tutorials :
I’m Mouna , developer from Tunisia . I love sharing knowledge and life experience .
If you have any questions , feel free to put a comment below .