How do I display a many-to-one relationship in a form drop-down list in Symfony2?

I have a form where I need to display the OneToMany relationship between let say car and its brand.

When I click on the drop-down list, now I can only see the name of the car. since it is automatically created from the vehicle object.

What I would like to see in my drop-down list is NameOfTheCar - NameOfTheBrand. For every choice

I have a CarType with a similar file:

$builder->add('cars', 'choice', array(
        'choices'   => array(
            'Test' => 'Example',
        ),
        'required'  => true,
    ));

How can i do this?

EDIT: I followed the advice of Hugo.

Now i got

$builder->add('lake', 'entity', array(
            'class'     =>  'Pondip\KeepnetBundle\Entity\CatchReport',
            'required'  => true,
        ));

And my __toString CatchReport

  public function __toString()
    {
        return $this->car .' - '. $this->car->getBrand();
    }

When the lake

/**
 * @var integer
 *
 * @ORM\ManyToOne(targetEntity="Pondip\CarBundle\Entity\Car")
 * @ORM\JoinColumn(name="car_id", referencedColumnName="id")
 * @Assert\NotBlank()
 */
private $car;

and in my brand essence I:

 /**
     * @var integer
     * @Assert\Type(type="Pondip\CarBundle\Entity\Brand")
     * 
     * @ORM\ManyToOne(targetEntity="Pondip\CarBundle\Entity\Brand")
     * @ORM\JoinColumn(name="brand_id", referencedColumnName="id")
     */
    private $brand;

And now I got an error from my toString () function. What have I done wrong?

thank

+5
source share
1

- 'entity', .

$builder->add('cars', 'entity', array(
        'class' => 'MyBundle:Car',

        // 'property' => 'myCustom', -- The default is the __toString() (Enity file)

        'query_builder' => function(EntityRepository $er) {
            return $er->createQueryBuilder('c')
                ; // You can add anything else here or
                  // use an existing function of the repository file
    ),
    'required'  => true,
));

property , , , , __toString() , property => 'myCustom'.

:

, , Cars.php( getter). property.

  • : toString

    function __toString(){
        return $this->name . " - ". $this->brand;
    }
    
  • :

    function getMyCustom(){
        return $this->name . " - ". $this->brand;
    }
    

query_builder.
, . , . , , . , ->findAll().


Update

__toString , ( ). - :

function __toString(){ // CatchReport
    return $this->car

}

function __toString(){ // Car
    return $this->name . " - " . $this->brand

}

function __toString(){ // Brand
    return $this->name

}

, , ,

+10

All Articles