Casey

Full-Stack Developer

#drupal8 #php

Attach an existing Entity field to a custom Form in Drupal 8

<?php
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

class CustomUserForm extends FormBase {
  
   public function buildForm(array $form, FormStateInterface $form_state) {
      $form['#parents'] = [];
     
      $entity = \Drupal::service('entity_type.manager')->getStorage('user')->create();
      $entity_form_display = \Drupal::service('entity_type.manager')->getStorage('entity_form_display')->load('user.user.default');
   
      if($widget = $entity_form_display->getRenderer('field_name')) {
          $items = $entity->get('field_name');
          $items->filterEmptyItems();
          $form['user_name'] = $widget->form($items, $form, $form_state);
          $form['user_name']['#access'] = $items->access('edit');
      }
   }
   
}
   
?>