As I said in my title, imagine I have one entity User and I want to create multiple form for this entity.
For example, this is my class User :
class User
{
protected $firstname;
protected $lastname;
protected $sex;
protected $birthdate
protected $phone;
protected $email;
protected $password;
}
Now I want to create multiple form for this entity :
- RegisterForm (ask every fields)
- ConnexionForm (ask email + password)
- ForgetPasswordForm (ask email)
- etc.
I find this solution and I'd like to know if it's the best practice or not :
In my "FormType", I configure my options like this :
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'AppBundle\Entity\User',
'fields' => false,
));
}
Then I create a loop for each fields I want :
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
if($options['fields']){
foreach($options['fields'] as $field){
$builder->add($field);
}
} else {
// Every field I want
}
}
And in my Controller, I can use it like this :
$form = $this->createForm(UserType::class,$user,['fields' => ['email','password', 'other...']);
With the same idea, I maybe can give a name to my different form and if I don't write a name in my "options" I create the "Register" form, if I write "connexion" I build the "Connexion" form, etc.
Do you have a better solution or it's the best way to do it?
(I know you can do it with FOSUserBundle, but I pick "User" for the example)