1

I've managed to create a new theme, customize the front page pretty much how I wanted it, and I've encountered a problem.

I need to get the register form (create new account) in a pop-up on the front page.

After following the instructions from Form API in Drupal 8:

    <?php

/**
* @file
* Functions to support theming in the themename theme.
*/

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Utility\UrlHelper;

/**
* Implements hook_preprocess_HOOK() for HTML document templates.
*/

function themename_preprocess_html(&$variables) {

$form = \Drupal::formBuilder()->getForm('Drupal\user\register');

return $form;
}

I can't figure out what I'm doing wrong, because I get an error saying that is not a valid form. I have also tried using the form id as a parameter, still no valid form.

Could anyone please help? I could use a working example.

1

The correct form id shoud be Drupal\user\RegisterForm. However, because the register form is attached to an entity, you can't use getForm directly. You need to create an entity and then get the register form for that entity.

The role of the preprocess function is to add / modify / delete template variables via the $variables parameter, so you need to add the form to that array rather than return it.

Something like this should work:

function themename_preprocess_page(&$variables) {  
  $entity = \Drupal::entityManager()
    ->getStorage('user')
    ->create(array());

  $formObject = \Drupal::entityManager()
    ->getFormObject('user', 'register')
    ->setEntity($entity);

  $form = \Drupal::formBuilder()->getForm($formObject);
  $variables['register_form'] = $form;
}

Now you should be able to print the form via {{ login_form }} in the page.html.twig template.

0

Alternatively, use the module FormBlock (https://www.drupal.org/project/formblock) to make the registration form available as a block, and then add a "popup" region to your theme, and using the blocks UI place the block in that region just for the front page.

0

This is working well for me at the moment:

$formBuilder = \Drupal::service('entity.form_builder');
$form = $formBuilder->getForm(User::create(array()), 'register', array());

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.