0

I need to prepopulate an entity refence field depending on a list selection field. If the user select liste "administrator" then ajax need to prepopulate the field with users asssociated to this list. I get the selected user ids, but I can't prepopulate the field. For testing, on click to a list I can create a field filled with good ID, so just need to prepopulate now..

public function buildForm(array $form, FormStateInterface $form_state) {

$form['#theme'] = 'message_form';
$form = parent::buildForm($form, $form_state);
$entity = $this->entity;

//original field which needs to be prepopulate
//$form['receiver_id']['#access'] = FALSE;
$form['destinataire_wrapper']['receiver_id'] = $form['receiver_id'];
unset($form['receiver_id']);

//added for logic

//the user select a sending list
$form['liste'] = [
  '#type' => 'select',
  '#title' => t("Liste d'envoi"),
  '#options' => $options,
  '#empty_option' => $this->t("- Sélectionner une liste d'envoi -"),
  '#weight' => -50,
  '#ajax' => [
    'callback' => '::updateDestinataire',
    'wrapper' => 'destinataire-wrapper',
  ],
];


$form['destinataire_wrapper'] = [
  '#type' => 'container',
  '#attributes' => ['id' => 'destinataire-wrapper'],
  '#weight' => -40,
];

$liste_envoi = $form_state->getValue('liste');

if (!empty($liste_envoi)) {
  $ids = $this->getDestinataires($liste_envoi);
  //here is the problem to prepopulate.....
  $form['destinataire_wrapper']['receiver_id'][] =$ids;    
}

return $form;}

public function updateDestinataire(array $form, FormStateInterface $form_state) {
return $form['destinataire_wrapper'];}                                 

protected function getDestinataires($liste_envoi) {    
 $query = \Drupal::entityQuery('annuaire');
 $condition_or = $query->orConditionGroup();
 $condition_or->condition('region', 62);
 $query->condition($condition_or);
 $nids = $query->execute();
 $resultat = entity_load_multiple('annuaire', $nids);

 if (!empty($resultat)) {   
    foreach($resultat as $record) {         
        $ids[] = $record->getId();          
    }
 return $ids;
 }

}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.