Is it possible to make a single form type to handle both of the below scenarios?
I’m working on an application where a “normal” user (e.g. ROLE_USER) can perform a task by filling out a form. When the record gets created, he is linked to the event table. Additionally the ROLE_ADMIN user can link people on their behalf (using the same form with an additional ‘user’ field), selecting the user from a list of users.
At the moment I have an “eventType” and an “eventAdminType” with 98% code duplication. I’ve read about transformers and also form events, but I’m not entirely sure how I can adapt them to my needs.
Form code of “eventType”:
$builder
->add(
'reservedSlots', 'choice', array(
'choices' => array('1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'),
'required' => true,
)
)
Form code of “eventAdminType”:
$builder
->add('user')
->add(
'reservedSlots', 'choice', array(
'choices' => array('1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5'),
'required' => true,
)
)
Entity code:
class EventUser
{
...
/**
* @ORM\OneToOne(targetEntity="User")
* @var type
*/
private $user;
...
// all the other fields
/**
*
* @ORM\Column(type="integer")
*/
private $reservedSlots
How would I create a single form type the above?
You could create form type classes for both of your types and have one extend another:
Here’s some additional info about creating form classes.