4

On a custom page I'm trying to load an user edit form with a specific form display. I'm able to load the form however I can't figure out how to load the form with the specific display.

This is what I have now:

public function content($substep) {

    $user = \Drupal::entityTypeManager()
      ->getStorage('user')
      ->load(1); // loading user 1 for test purpose

    $form_state = new FormState();

    $form = \Drupal::entityTypeManager()
      ->getFormObject('user', 'default')
      ->setEntity($user);

    return \Drupal::formBuilder()->getForm($form);
}

Anyone has an idea?

  • What do you mean by 'specific display'? Forms don't have display modes, that's only for viewing entities. – Jaypan Mar 7 '17 at 2:07
  • 1
    It's technically called a "form mode" @Jaypan but D8 does have them – Clive Mar 7 '17 at 7:56
  • Interesting. Some more research has shown me more about this. I didn't even realize this existed in D8. – Jaypan Mar 7 '17 at 8:04
7

In D8 you can add display modes for forms in UI. But these form modes can't be used right away like view modes.

If you want to use a form mode in code you have to set a form operation with the same name in the handlers section of the entity type. The form class you use for this handler is the same as in the default handler, because you want to control which fields are displayed in the form mode, not in a different form class.

For example to use a form mode profile2, which you have configured in UI, you have to add a form operation profile2 to the user entity type definition in a hook_entity_type_build:

mymodule.module

function mymodule_entity_type_build(array &$entity_types) {
  $entity_types['user']->setFormClass('profile2', 'Drupal\user\ProfileForm');
}

Then you can use the new form operation (form mode) in the code example from the question:

public function content($substep) {

  $user = \Drupal::entityTypeManager()
    ->getStorage('user')
    ->load(1); // loading user 1 for test purpose

  $form_state = new FormState();

  $form = \Drupal::entityTypeManager()
    ->getFormObject('user', 'profile2')
    ->setEntity($user);

  return \Drupal::formBuilder()->getForm($form);
}
  • 3
    Loading the $form_state isn't necessary. Also, keep in mind that when creating a form mode for the user entity with machine name user.profile2, for example, only profile2 is needed in code, as shown above. – Shaun Dychko Jan 9 '18 at 20:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.