I want to pass an object from controller to my form builder so I can use it later on for my ChoiceType field. How do I accomplish that?
This is my controller:
$choices = [];
$table2Repository = $this->getDoctrine()->getRepository('SwipeBundle:Company');
$table2Objects = $table2Repository->findAll();
foreach ($table2Objects as $table2Obj) {
$choices[$table2Obj->getId()] = $table2Obj->getId() . ' - ' . $table2Obj->getName();
}
$form = $this->createForm(SubAgentType::class, $choices, array(
'action'=>$this->generateUrl('backend_sub_agent_create'),
'method'=>'POST'
));
This is my SubAgentType.php
class SubAgentType extends AbstractType {
protected $choices;
public function __construct (Choices $choices)
{
$this->choices = $choices;
}
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('company_id', ChoiceType::class, array(
'mapped' => false,
'choices' => $choices,
));
The problem is I get the error below.
Catchable Fatal Error: Argument 1 passed to MyBundle\Form\SubAgentType::__construct() must be an instance of MyBundle\Form\Choices,
To respond to your question :
in your services.yml file :
myform.type:
class: AppBundle\Form\MyFormType
arguments:
- '@doctrine.orm.entity_manager'
tags:
- { name: form.type }
in your MyFormType :
/**
* @var EntityManagerInterface
*/
protected $em;
/**
* LicenseeType constructor.
*
* @param EntityManagerInterface $em
*/
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$choices = [];
$table2Repository = $this-em->getRepository('SwipeBundle:Company');
$table2Objects = $table2Repository->findAll();
foreach ($table2Objects as $table2Obj) {
$choices[$table2Obj->getId()] = $table2Obj->getId() . ' - ' . $table2Obj->getName();
}
...
But, clearly, you don't need to do that if you correctly define your entities relations.
Try to resolve your constructor in SubAgentType, $choices doesn't need to be a subtype of Choices:
public function __construct ($choices)
{
$this->choices = $choices;
}
If you inject an array in your controller, then the constructor must accept an array.