1

In a custom content entity, I have defined this field

$fields['from_seliste_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Offreur'))
  ->setDescription(t('Le SÉListe qui a rendu le service (qui reçoit les graines)'))
  ->setSetting('target_type', 'person')
  ->setSetting('handler', 'views')
  ->setSetting('handler_settings', [
    'view' => [
      'view_name' => 'sel_selistes',
      'display_name' => 'entity_reference_1',
    ],
  ])
  ->setDisplayOptions('view', array(
    'weight' => $weight,
  ))
  ->setDisplayOptions('form', array(
    'weight' => $weight,
    'type' => 'options_select',
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setRequired(TRUE);

In the corresponding form, the field appears as wanted as a dropdown list populated with the result of the View sel_selistes:
enter image description here

I'd like to create another form with the same functionality.
How should I code the field in the form?

$form['mySelectField'] = array(
  '#type' => 'select',
  '#options' => [], <-- ??????
  '#title' => $this
    ->t('whatever'),
);
2
  • I'd like to create another form with the same functionality copy paste? or you mean on a non entity form?
    – No Sssweat
    May 7 '19 at 10:03
  • on a non entity form!
    – gbmapo
    May 7 '19 at 10:09
1

I don't have time to provide an exact answer, but something along these lines.

// Programmatically execute view
$view = views_get_view('sel_selistes'); //  view machine name
$view->set_display("entity_reference_1"); // view display name
// $view->set_arguments($arg) // looks like you don't have arguments.
$view->execute();

$view_results = []; // create array
// loop through results
foreach ($view->result as $row_id => $row) {
  // some php magic so you add to array like this $view_results[$nid_value] = $some_field_row_value;
}

$form['my_select_field'] = array(
  '#type' => 'select',
  '#options' => $view_results,
  '#title' => $this
    ->t('whatever'),
);

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.