This tutorial shows you how to render the core login form in our template, or using this you can render any form in your template files according to your customization.
We know the drupal 8 uses the form builder to make the form, there is also getform function that get the form components and renderer servcie will render it.
let see how will you achieve this.
firstly we get the form and
$form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
next need to render it, so it can we view it drupal 8 twig format
$render = Drupal::service('renderer');
$output_form = $render->renderPlain($form);
You can achieve this in the hook like in
hook_preprocess_page
so lastly the complete example how you can combine that and put in page variable
function THEMENAME_preprocess_page(&$variables) {
$variables['render_login_form'] = FALSE; // For auth users it not visible and guest users will see that
if (!\Drupal::currentUser()->id()) {
$form = Drupal::formBuilder()->getForm(Drupal\user\Form\UserLoginForm::class) ;
$render = Drupal::service('renderer');
$variables['render_login_form'] = $render->renderPlain($form);
}
}
Now render in template using
{{render_login_form}}
You can also render different form in similar manner just need to check the right class under "core/modules/user"
similarily you can render register form using one line replacment
function THEMENAME_preprocess_page(&$variables) {
$variables['render_register_form'] = FALSE; // For auth users it not visible and guest users will see that
if (!\Drupal::currentUser()->id()) {
$form = Drupal::formBuilder()->getForm(Drupal\user\RegisterForm::class) ;
$render = Drupal::service('renderer');
$variables['render_register_form'] = $render->renderPlain($form);
}
}
I hope the article helps you, let us know by comment below
thanks
- Log in to post comments