2

I have seen Use dropdown in views exposed filter on text fields with node->title? but I need to use there a field from a paragraph field of the node. Let's say the paragraph field in the node is called field_pdfs and the field in the paragraph is called field_pdf_title. (node -> field_pdfs -> field_pdf_title). I tried the following code:

function pdf_app_form_views_exposed_form_alter(&$form, FormStateInterface $form_state, $form_id) {

// If not the view we are looking, move on


// Query nodes
$storage = Drupal::getContainer()->get('entity_type.manager')->getStorage('node');
$nids = $storage->getQuery();

// Gather published artist nodes and sort by title
$nids = $nids->condition('type', 'library')
 ->condition('status', 1)
 ->sort('title')
 ->execute();

// If there are no nodes, move on
if (!$nids) {
 return FALSE;
}

// Start building out the options for our select list
$options = [];
$nodes = $storage->loadMultiple($nids);

// Push titles into select list
foreach ($nodes as $node) {

$result = $node->get('field_pdfs')->referencedEntities();
foreach ($result as $paragraph) {
  if ($paragraph instanceof Paragraph) {
    $value = $paragraph->field_pdf_title;
 $options[$value] = $value;
  }


 }
  }

// Start building out our new form element
 $form['field_pdf_title']['#type'] = 'select';
$form['field_pdf_title']['#options'] = $options;
$form['field_pdf_title']['#size'] = 1;
 }
  • 2
    You almost had it, needs to be $value = $paragraph->field_pdf_title->value; When getting an Entity/Node's title just happens to not require the ->value part, but fields do. – No Sssweat Mar 1 at 3:19
  • Yes thank you it is working! – rebecca mantel Mar 1 at 10:15
  • Also viable: $paragraph->get('field_pdf_title')->getString() or $paragraph->get('field_pdf_title')->first()->getValue() (getValue returns an array without first() first) – Beebee Mar 1 at 15:33
  • Thank you it is working! The only problem is that it shows me all the paragraphs and not just the ones belonging to the current node. Any leads? – rebecca mantel Mar 26 at 21:20

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.