1

I'm using snippet code:

$user = User::create([
      'mail' => '[email protected]',
      'name' => 'user_name',
    ]);
// $user->save();   I don't want create user here.
$form = \Drupal::entityTypeManager()
  ->getFormObject('user', 'default')
  ->setEntity($user);
return \Drupal::formBuilder()->getForm($form);

or

$user = User::create([
  'mail' => '[email protected]',
  'name' => 'user_name',
]);

return $this->entityFormBuilder()->getForm($user);

on my controller to render user form to custom page. I want to this form have some default value. Example mail and username. I don't want to use hook form alter.

Other way to set default value for entity form?

Update: a way I tried:

  • Extend class RegisterForm
  • Override method form
  • Tried two method $form_state->setStorage() and $form_state->setUserInput() like on NodeForm

But doesn't working.

5
  • Your last example seems to be pretty much straightforward, why you are asking?
    – 4uk4
    Commented Mar 3, 2018 at 12:37
  • @4k4 I try it. But form still don't have default value. Or you say about hook_form_alter?
    – Jonh
    Commented Mar 3, 2018 at 12:40
  • Tried it too, and indeed, it doesn't work. It does work for Node::create([...]) though. What is special about the user entity here?
    – 4uk4
    Commented Mar 3, 2018 at 12:59
  • I want to change follow register user. Wait user register verify by email before create user.
    – Jonh
    Commented Mar 3, 2018 at 13:03
  • 2
    The difference between user and node is that node uses widgets, while the user form still uses custom code for those elements. User also has a custom register form mode with special logic for new users. In short, there is no way to do this without using form alter
    – Berdir
    Commented Mar 4, 2018 at 10:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.