简体   繁体   中英

default data in sonata_type_model

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

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
        )
    );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM