Created
March 29, 2024 14:42
-
-
Save aklump/d11146c83c2718e3f4b068312dea4a62 to your computer and use it in GitHub Desktop.
Drupal form widget to preset entity ref with current user.
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 | |
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