Last active
November 2, 2022 10:04
-
-
Save MikeNGarrett/8db8f0ac2a109a17bff5762e0aa2100c to your computer and use it in GitHub Desktop.
Drupal curated autocomplete field
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\Core\Form\FormStateInterface; | |
function hook_field_widget_complete_entity_reference_autocomplete_form_alter(&$field_widget_complete_form, $form_state, $context) | |
{ | |
if($field_widget_complete_form['widget']['#field_name'] !== 'field_test') { | |
return; | |
} | |
$storage = Drupal::getContainer()->get('entity_type.manager')->getStorage('node'); | |
$nids = $storage->getQuery(); | |
// Gather published artist nodes and sort by title | |
$nids = $nids->condition('type', 'article') | |
->condition('status', 1) | |
->range(1, 10) | |
->sort('title') | |
->execute(); | |
if (!$nids) { | |
return false; | |
} | |
$nodes = $storage->loadMultiple($nids); | |
$temp = $field_widget_complete_form['widget'][0]; | |
foreach($nodes as $node) { | |
$temp['target_id']['#default_value'] = $node; | |
$field_widget_complete_form['widget'][] = $temp; | |
} | |
$field_widget_complete_form['widget'][] = $field_widget_complete_form['widget'][0]; | |
unset($field_widget_complete_form['widget'][0]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment