6

To load the login form I am using the following code.

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

I would like to load the form to create or edit a node. How can I achieve this?

16

Copying partially from an answer that I gave here: How to alter $form_state before render a form?

To get an add form, you can have to do something like this:

$values = array('type' => $node_type);

$node = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($values);

$form = \Drupal::entityTypeManager()
  ->getFormObject('node', 'default')
  ->setEntity($node);
return \Drupal::formBuilder()->getForm($form);

Edit: Somehow I missed that you said edit. You do exactly the same then, except that you don't create a new $node, you load the one you want to edit and then use that.

As written there, this is based on the entityblock_form module, so if you need this in a block, you can also just use that module.

  • Thanks for your help, I have implemented same for profile form, it works, Along with address fields I have the country, stage fields, which is an Ajax enabled. form alter is disturbing on ajax call, I want to call a function on #after_build, but it's not invoking. please help – allabakash.g Jun 16 '17 at 10:14
  • If you are in a controller, there's an easier way to get the node add form. After creating the new node object as in Berdir's code above, you can simply use: $form_render_array = $this->entityFormBuilder()->getForm($node); – Giles B Oct 22 '17 at 21:38
  • Awesome hint, kudos to Berdir – Stefan Korn Nov 21 '17 at 17:25

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.