2

I'm trying to port a theme from Drupal 6 to Drupal 8, and I find code like the following.

$edit = array();
$edit['nid'] = $node->nid;
$form = drupal_get_form('comment_form', $edit));

How do I load the form in Drupal 8? I get the following error:

Fatal error: Call to a member function getEntityTypeId() on null in /www/site/core/lib/Drupal/Core/Entity/EntityForm.php on line 77

The line causing the error is the following one:

\Drupal::formBuilder()->getForm('Drupal\comment\CommentForm');

I can't work out how to pass the node object to the form builder. How can I do it?

3 Answers 3

2

kiamlaluno's solution didn't work for me. This did:

$values = array(
    'entity_type'  => 'node',
    'entity_id'    => $node->id(),
    'field_name'   => 'comment',
    'comment_type' => 'comment',
    'pid' => NULL,
);

$comment = \Drupal::entityTypeManager()->getStorage('comment')->create($values);
$formHTML  = \Drupal::service('entity.form_builder')->getForm($comment);
2

FormBuilder::getForm() doesn't accept just a single argument; it accepts additional arguments that are passed to the functions called by FormBuilder::getForm(), including the unique form constructor function. These values are available to implementations of hook_form_alter() and hook_form_FORM_ID_alter() as $form_state->getBuildInfo()['args'].

To build an entity form, though, Drupal core uses the entity.form_builder service instead of form_builder. The following is the code used in CommentLazyBuilders::renderForm() to build the comment form.

$values = [
  'entity_type' => $commented_entity_type_id,
  'entity_id' => $commented_entity_id,
  'field_name' => $field_name,
  'comment_type' => $comment_type_id,
  'pid' => NULL,
];
$comment = $this->entityTypeManager->getStorage('comment')
  ->create($values);

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

EntityFormBuilder::getForm() accepts two arguments more; the second one is the operation to be done on the entity. Passing 'delete' as second argument, the code would obtain the form to delete the entity.

0
1

Example in core using lazy builder approach to make it work properly with caching per permission

http://cgit.drupalcode.org/drupal/tree/core/modules/comment/src/Plugin/Field/FieldFormatter/CommentDefaultFormatter.php#n194

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.