How to render user login form and user register form in Drupal 8

Posted by admin on Thu, 06/29/2017 - 10:04

I've spend an hour to understand how to render user login form and user register form in Drupal 8 to print them in a custom place.
Here is the solution.

Lets say you want to print those two forms in a custom place on your page (in a popup in my case).

So if you THEMENAME.theme file write this first:

function THEMENAME_preprocess_page(&$variables) {
}

User login form

$form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
$render = Drupal::service('renderer');
$variables['login_form'] = $render->renderPlain($form);

User registration form

    $entity = \Drupal::entityTypeManager()->getStorage('user')->create(array());
    $formObject = \Drupal::entityTypeManager()
      ->getFormObject('user', 'register')
      ->setEntity($entity);
    $form = \Drupal::formBuilder()->getForm($formObject);
    $variables['register_form'] = \Drupal::service('renderer')->render($form);

The final step would be to output the results using your twig template.
For example in page.html.twig you just write to ouput the login form:

{{ login_form }}

Or register form:

{{ register_form }}
×

Hey! Don't miss a new cool stuff!

Comments

summer (not verified)

Thanks! I'm sure you saved me a ton of time and one less module!

sudharson (not verified)

Thanks, it saves me lot of time

Julius (not verified)

Thanks, works good on pages. If I try to use it on nodes it produces an error. Do I have to change anything if I have THEMENAME_preprocess_node ?

Add new comment