Last active
June 21, 2021 18:29
-
-
Save msankhala/27da2c67877a4e2691278091065d092e to your computer and use it in GitHub Desktop.
Creating custom Entity Display form mode
This file contains 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 | |
// Source https://www.droptica.com/blog/custom-entity-forms-example-user-editing-and-registration/ | |
/** | |
* Implements hook_entity_type_build(). | |
*/ | |
function my_module_entity_type_build(array &$entity_types) { | |
$form_modes = ['custom_form_mode_1', 'custom_form_mode_2']; | |
foreach ($form_modes as $mode) { | |
$entity_types['user']->setFormClass($mode, 'Drupal\user\ProfileForm'); | |
} | |
} | |
# Add route to you my_custom_module.routing.yml | |
my_custom_module.user.edit_form: | |
path: '/user/{user}/custom-form-mode-1' | |
defaults: | |
_entity_form: user.custom_form_mode_1 | |
_title: 'User entity custom form mode 1' | |
requirements: | |
_permission: 'required permission goes here' | |
# Loading custom entity form mode programmatically in a block | |
$entity_type_id = 'user'; | |
$form_mode = 'my_custom_form_mode_2'; | |
$userForm = $entityTypeManager->getEntityForm($entity_type_id, $form_mode); | |
$existingUser = $entityTypeManager->getStorage('user')->load($user_id); | |
// or | |
$newUser = $entityTypeManager->getStorage('user')->create(); | |
$userForm->setEntity($existingUser); | |
// or | |
$userForm->setEntity($newUser); | |
$form = \Drupal::formBuilder()->getForm($userForm); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment