Reputation: 3440
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 :
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)
Upvotes: 0
Views: 79
Reputation: 431
You can do it like you wrote.
But i think better solution is to write specialized php form classes. Than you would have types like you wrote. But form classes are called with Type word in Symfony:
RegisterType (ask every fields)
ConnectionType (ask email + password)
ForgetPasswordType (ask email)
Here you have Best Practices and more tips from Symfony (first paragraph is about forms): http://symfony.com/doc/2.8/best_practices/forms.html
Upvotes: 1