问题描述:

I have this code inside my ClutchType

public function buildForm(FormBuilderInterface $builder, array $options)

{

$currentUser = $this->currentUser;

$builder

->add('breedingPair')

->add('breedingPair', 'entity', array(

'class' => 'Breedr\BreedingPairsBundle\Entity\Pairs',

'property' => 'id',

'property' => 'breeding_pair_male',

'placeholder' => 'Choose a breeding pair',

'query_builder' => function(EntityRepository $er) use ($currentUser) {

return $er->createQueryBuilder('br')

->where('br.user = :currentUser')

->orderBy('br.breedingPairDate')

->setParameter('currentUser', $currentUser);

}

))

->add('laidDate')

->add('estimatedHatchStart')

->add('estimatedHatchEnd')

->add('hatchDate')

->add('eggAmount')

->add('breedingSeason')

;

}

Which works fine and brings out the male inside a breeding pair. How can i make it so it shows both the male and the females name in the drop down? I've tried:

public function buildForm(FormBuilderInterface $builder, array $options)

{

$currentUser = $this->currentUser;

$builder

->add('breedingPair')

->add('breedingPair', 'entity', array(

'class' => 'Breedr\BreedingPairsBundle\Entity\Pairs',

'property' => 'id',

'property' => 'breeding_pair_male',

'property' => 'breeding_pair_female',

'placeholder' => 'Choose a breeding pair',

'query_builder' => function(EntityRepository $er) use ($currentUser) {

return $er->createQueryBuilder('br')

->where('br.user = :currentUser')

->orderBy('br.breedingPairDate')

->setParameter('currentUser', $currentUser);

}

))

->add('laidDate')

->add('estimatedHatchStart')

->add('estimatedHatchEnd')

->add('hatchDate')

->add('eggAmount')

->add('breedingSeason')

;

}

But obviously you can't show more than one value in the property.

So what i have at the moment looks like this:

But i would like it to show both the male and female names next to each other. Currently it is only pulling the male's name.

Here is my SQL table that shows there is an ID for a male and a female

网友答案:

The property option in your ->add('breedingPair', 'entity' call can be set to any user-defined method you like, so within your Breedr\BreedingPairsBundle\Entity\Pairs entity you could define a method that returns the string you want, e.g.

public function getPairAsString()
{
    return sprintf(
        '%s & %s', 
        $this->breedingPairMale->getName(), 
        $this->breedingPairFemale->getName()
    );
}

and then in your ClutchType you would add the field as follows:

$builder->add('breedingPair', 'entity', array(
    'class' => 'Breedr\BreedingPairsBundle\Entity\Pairs',
    'property' => 'pairAsString',
    'placeholder' => 'Choose a breeding pair',
    'query_builder' => function(EntityRepository $er) use ($currentUser)         {
        return $er->createQueryBuilder('br')
            ->where('br.user = :currentUser')
            ->orderBy('br.breedingPairDate')
            ->setParameter('currentUser', $currentUser);
    }
))
相关阅读:
Top