1

I have created two templates

page--node--edit.html.twig

page--node--add.html.twig

I have discovered that the {{ node }} and {{ node_form }} variables are missing during node creation.

Here is my code to render the node add form there using hook_preprocess_page.

  $variables['node_form'] = FALSE;
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $form = \Drupal::entityTypeManager()
        ->getFormObject('node', 'default')
        ->setEntity($node);
      $variables['node_form'] = \Drupal::formBuilder()->getForm($form);
   }

My goal is to print node content type name and form from page--node--add.html.twig template.

PS. No issue on page--node--edit.html.twig (node edit page)

0
if ($node = \Drupal::routeMatch()->getParameter('node')) { 

There's no node ID in the route at /node/add/foo, so there's no node available, and that condition will always be false.

You need to create the node yourself, e.g.

// Get the desired type from the route.
if ($node_type = \Drupal::routeMatch()->getParameter('node_type')) {
  $node = \Drupal::entityTypeManager()
    ->getStorage('node')
    ->create([
      'type' => $node_type->id(),
    ]);

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

  $variables['node_form'] = \Drupal::formBuilder()->getForm($form);
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy