Einius
Einius

Reputation: 1382

Symfony2 doctrine dropdown menu select choices from related entity

I have two entities: Event and City. And I want to implement create event form. but one of the fields should be dropdown list with the values from database (City entity).

currently I have that in my controller:

$city = $this->getDoctrine()
    ->getRepository('AtotrukisMainBundle:City')
    ->findBy(
        array(),
        array('priority' => 'ASC', 'name' => 'ASC')
    );


$event = new Event();

$form = $this->createFormBuilder($event)
    ->add('name', 'text')
    ->add('description', 'textarea')
    ->add('startDate', 'datetime')
    ->add('endDate', 'datetime')
    ->add('map', 'text')
    ->add('city', 'choice', array(
        'choice_list' => new ChoiceList($city->getId(), $city->getName())
    ))
    ->add('save', 'submit', array('label' => 'Sukurti'))
    ->getForm();

$form->handleRequest($request);

But with that I get error: Error: Call to a member function getId() on array in /var/www/src/Atotrukis/MainBundle/Controller/EventController.php line 31

Upvotes: 1

Views: 2445

Answers (3)

Ashwin
Ashwin

Reputation: 460

Please check this:

->add('usr_role', EntityType::class, array('label' => 'Role : ',
     'class' => \Ibw\UserBundle\Entity\UserRole::class,
     'expanded' => false, 'placeholder' => 'Select Role',
     'multiple' => false))

Upvotes: 0

jamek
jamek

Reputation: 812

It's move clear to keep this things out of controller - more readable.

->add('approvers', 'entity', array(
    'class' => 'YourBundle:Entity',
    'query_builder' => function(EntityRepository $er) {
        return $er->orderBy('name', 'ASC'); // Here you can make some custome query
     },
     'label' => 'label',
))

Upvotes: 1

Damaged Organic
Damaged Organic

Reputation: 8467

Anyway, solution could be:

foreach($city as $value) {
    $id_set[]   = $value->getId();
    $name_set[] = $value->getName();
}

//...

->add('city', 'choice', array(
    'choice_list' => new ChoiceList($id_set, $name_set)
))

Because ChoiceList expects an arrays as arguments. You are trying to use methods on array.

Upvotes: 1

Related Questions