1

I understand that users could use 'add content' from the admin menu, but I'm building a custom block plugin or form so the add content form can be displayed in a block on the page instead of requiring users to use an actual admin page. I've done this before by manually creating forms in a render array in a form plugin that save the field values into a node upon form submit, but it'd nice to actually be able to just grab the actual add node form and render it directly.

In my research I found code to do this for Drupal 7

module_load_include('inc', 'node', 'node.pages');
$node_form = new stdClass;
$node_form->type = 'yourContentType';
$node_form->language = LANGUAGE_NONE;
$form = drupal_get_form('yourContentType_node_form', $node_form);
return $form;

But I need a way to do this in Drupal 8. I've loaded custom form controllers before like so

$content = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyForm');

But I'm not sure how I would add a specific 'add content' form. How would I get the form of any 'add content' for a specific content type?

UPDATE: I found a path to something called 'NodeForm' and I tried to use it like so

$content = \Drupal::formBuilder()->getForm('Drupal\node\NodeForm\publication');

Where publication was a content type I wanted to load the form for. But I receive an error

The form argument Drupal\node\NodeForm\publication is not a valid form

And out of curiosity I tried

$content = \Drupal::formBuilder()->getForm('Drupal\node\NodeForm');

But that gives me the error

Fatal error: Call to a member function getEntityTypeId() on null in /Library/WebServer/Documents/aaep/web/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

1
  • 1
    Note that there are already various modules available that provide entity form as a block functionality, for example drupal.org/project/entityform_block (Disclaimer: I'm a maintainer)
    – Berdir
    Dec 22, 2016 at 19:55

1 Answer 1

5

Entity forms are built by EntityFormBuilder::getForm(). The parameter is an entity not a form class. This can be an existing entity or a new entity to add content.

For example to add content for the content type article you create this entity:

$node = \Drupal\node\Entity\Node::create(['type' => 'article']);

Use the new entity to build the form:

$form = \Drupal::service('entity.form_builder')->getForm($node);
1
  • Hello, and to submit it programmatically? tried with submitForm but it does not work. Aug 3, 2018 at 9:43

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.