Skip to content

Instantly share code, notes, and snippets.

@aklump
Created March 29, 2024 14:42
Show Gist options
  • Save aklump/d11146c83c2718e3f4b068312dea4a62 to your computer and use it in GitHub Desktop.
Save aklump/d11146c83c2718e3f4b068312dea4a62 to your computer and use it in GitHub Desktop.
Drupal form widget to preset entity ref with current user.
<?php
namespace Drupal\se_core\Plugin\Field\FieldWidget;
use Drupal;
use Drupal\Component\Utility\Color;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\Plugin\Field\FieldWidget\EntityReferenceAutocompleteWidget;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\se_core\Seao;
use Drupal\user\Entity\User;
/**
* Plugin implementation of the 'current_user' widget.
*
* @FieldWidget(
* id = "current_user",
* module = "se_core",
* label = @Translation("Current User"),
* field_types = {
* "entity_reference"
* }
* )
*/
class CurrentUserWidget extends EntityReferenceAutocompleteWidget {
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$account = User::load(Drupal::currentUser()->id());
if (empty($element['target_id']['#default_value'])) {
$element['target_id']['#default_value'] = $account;
}
return $element;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment