I have modified directly a FOSUserForm (with no overriding) to try and assign a default value while building the form, I have added the
array('data'=>'default value')
such as:
namespace FOS\UserBundle\Form\Type;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
class RegistrationFormType extends AbstractType
{
private $class;
/**
* @param string $class The User class name
*/
public function __construct($class)
{
$this->class = $class;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('data' => 'Default value','label' => 'form.username', 'translation_domain' => 'FOSUserBundle'))
->add('email', 'email', array('data' => 'Default value','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' => $this->class,
'intention' => 'registration',
));
}
public function getName()
{
return 'fos_user_registration';
}
It doesn’t work and I keep having a form validation message “Please enter a username”
what’s wrong?
Have you tried setting the username as a hidden field instead of “null”? Or remove the username from the form completely and set it manually before the entity is persisted in the database. I don’t recommend the second option unless you have performed a check to make sure the username is unique before persisting it to the database.
Edit:
Out of curiousity, why are you modifying a vendor class directly?
Edit 2:
The default validation for the username field should probably not be removed (and if you do, make sure it is still a unique field in the database (http://symfony.com/doc/2.0/reference/constraints/UniqueEntity.html).
If you want to set a default username value, instead of setting the data option in the form, create a custom RegistrationFormHandler that overrides the default createUser method:
Instructions on overriding this handler can be found here (towards the bottom):
https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/overriding_forms.md
It’s pretty simple, should only take a minute to implement. Additionally, creating the custom formhandler will also prevent any changes you’ve made in the vendor classes from being lost when you update your vendors via composer.
Edit 3:
DependencyInjection\EtienneUserExtension.php:
services.xml