php - Symfony formtype query builder associations
Get the solution ↓↓↓I'm with Symfony 3.2, and I would like to have a form type for an entity that is associated to another one:
class Aliment
// ...
private enseigneId;
// ...
and
class Enseigne
// ...
private nomEnseigne
// ...
and Aliment.enseigneId refers to Enseigne.id, but what I want to make in my form (CRUD, for the creation one) is to let the user choising an ID but I want to display the value of that ID instead, so it's easier for the user.
This is what I have in my form type (Ticket) :
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('date', DateTimeType::class, array(
'data' => new \DateTime()
))
->add('aliments')
->add('prixTotal')
->add('recapitulatif')
->add('modePaiement')
->add('enseigneId', EntityType::class, array(
'class' => 'AppBundle\Entity\Enseigne',
'choice_label' => function ($enseigne) {
/** @var $enseigne Enseigne */
return $enseigne->getNomEnseigne();
}
));
}
But it keeps displaying the integer 0 instead (while getNomEnseigne() return a string and the database is well filled with correct dataset), I don't know how to do.. I want it to be stored as an integer, but I want to display (in the choice field) as the value of the Id it's referring to.
Id | nomEnseigne | ...
With the above example, the user would see the string "LECLERC" but the integer 0 would be stored instead.
Thank you for your help.
Answer
Solution:
you can try other ways like
'choice_label' => 'nomEnseigne',
or realizing __toString() method of Enseigne entity
/**
* @return string
*/
public function __toString()
{
if (empty($this->nomEnseigne) {
return 'enseigne ' . $this->id;
}
return (string) $this->nomEnseigne;
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: can't write image data to path
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.