Skip to content
Snippets Groups Projects

Issue #2702401: Add integration for the user entity type

2 unresolved threads
2 files
+ 92
0
Compare changes
  • Side-by-side
  • Inline
Files
2
+ 88
0
<?php
namespace Drupal\inline_entity_form\Form;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element;
use Drupal\user\AccountForm;
/**
* User inline form handler.
*/
class UserInlineForm extends EntityInlineForm {
protected ?AccountForm $accountForm;
protected ?FormStateInterface $accountFormState;
public function getEntityTypeLabels() {
return [
'singular' => $this->entityType->getSingularLabel(),
'plural' => $this->entityType->getPluralLabel(),
];
}
public function entityForm(array $entity_form, FormStateInterface $form_state) {
$user_form_object = $this->getUserFormObject($entity_form['#entity'], $form_state, $entity_form['#form_mode']);
// Copy user base fields items into the main entity form object.
$user_form = $user_form_object->form($entity_form, $form_state);
foreach (Element::children($user_form) as $field_name) {
$entity_form[$field_name] = $user_form[$field_name];
}
return parent::entityForm($entity_form, $form_state);
}
/**
* Builds an updated entity object based upon the submitted form values.
*/
protected function buildEntity(array $entity_form, EntityInterface $entity, FormStateInterface $form_state) {
/** @var \Drupal\user\UserInterface $entity */
parent::buildEntity($entity_form, $entity, $form_state);
$this->accountFormState = clone $form_state;
$this->accountFormState->setValues($form_state->getValue($entity_form['#parents'])['account']);
$user_entity = $this->accountForm->buildEntity($entity_form, $this->accountFormState);
foreach ($user_entity->getFields() as $field_name => $field_value) {
$entity->set($field_name, $field_value->getValue());
}
// Uncomment to allow resubmitting the form without having to face
// integrity constraint error on every submit.
// $entity->setEmail(uniqid() . '@example.com');
}
/**
* Internal helper.
*
* Returns handler for the user form.
*
* @param \Drupal\Core\Entity\ContentEntityInterface $entity
* User account entity.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Current form state.
* @param string $form_mode
* User form mode (usually it's "register").
*
* @return \Drupal\Core\Form\FormInterface
* User account form.
*/
protected function getUserFormObject(
EntityInterface $entity,
FormStateInterface $form_state,
string $form_mode
): AccountForm {
/** @var \Drupal\user\RegisterForm $user_form_object */
$this->accountForm = $this->entityTypeManager->getFormObject($entity->getEntityTypeId(), $form_mode);
$this->accountForm->setEntity($entity);
$form_display = $this->getFormDisplay($entity, $form_mode);
$this->accountForm->setFormDisplay($form_display, $form_state);
return $this->accountForm;
}
}
Loading