Reputation: 260
I work with symfony 2.7 , and I use SonataAdminBundle.
I have 2 entities called (Produit) and (Correspondant) with OneToMany relation, One Produit can have Many Correspondant. in the create form for the (Produit) I have correspondants to add Many (Correspondant), and I like by default add all the Correspondants, for that I tried to do this :
ProduitAdmin
$query = $this->modelManager->getEntityManager(new User())->createQuery("SELECT s FROM UserBundle\Entity\User s WHERE s.type LIKE 'Correspondant'" );
$formMapper
->add('correspondants','sonata_type_model', array(
'class'=>'Devagnos\UserBundle\Entity\User',
'multiple'=> true,
'by_reference' => false,
'label'=>'Correspondants associés',
'data' => function() {
$data = new ArrayCollection();
$r= $query->getResult();
foreach($r as $result) {
$data->add($result->getId());
}
return $data;
},
'query' => $query ),
)
But this does not work,
Someone can help me please ? thanks
Upvotes: 0
Views: 505
Reputation: 984
You need to set data
attribute and put the entities you want to be selected as default.
$selected = ... //fetch entities, e.g. from repository
$formMapper
->add('field', 'sonata_type_model', array(
'your_settings' => '...',
'query' => '...',
'data' => $selected
)
);
Upvotes: 2