In this example, I created a form which is used to register a new user. In the options passed to the form, I give the different roles a user can have.
Creating a reusable class for my form with configured data class and an extra option that fills the choice field to pick a userrole:
class UserType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('firstName', TextType::class, array(
'label' => 'First name'
))
->add('lastName', TextType::class, array(
'label' => 'Last name'
))
->add('email', EmailType::class, array(
'label' => 'Email'
))
->add('role', ChoiceType::class, array(
'label' => 'Userrole',
'choices' => $options['rolechoices']
))
->add('plain_password', RepeatedType::class, array(
'type' => PasswordType::class,
'first_options' => array('label' => 'Password'),
'second_options' => array('label' => 'Repeat password')
))
->add('submit', SubmitType::class, array(
'label' => 'Register user'
));
}
public function configureOptions(OptionsResolver $optionsResolver)
{
$optionsResolver->setDefaults(array(
'data_class' => 'WebsiteBundle\Entity\User',
'rolechoices' => array()
));
}
}
As you can see, there's a default option added to the form named 'roleChoises'. This option is created and passed in the method to create a form object. See next code.
Creating a form-object in my controller:
$user = new User();
$roles = array(
'Admin' => User::ADMIN_ROLE,
'User' => User::USER_ROLE
);
$form = $this->createForm(UserType::class, $user, array(
'rolechoices' => $roles
));