1

I want to render a form in a node view. I made an entity reference to a contact form, then in the preprocess_node I'm trying to get the render array of the contact form.

function mysupertheme_preprocess_node(&$variables) {
  $node = $variables['node'];

  if ($node->getType() == 'mynodetype') {
    if (!empty($node->field_mynodetype_form->referencedEntities())) {
      $contact_form = $node->field_mynodetype_form->referencedEntities()[0];
      $message = \Drupal::entityManager()
      ->getStorage('contact_message')
      ->create(array(
        'contact_form' => $contact_form->id(),
      ));

      //$form = \Drupal::entityFormBuilder()->getForm($message);
    };
  }
}

I don't know how to call entityFormBuilder in preprocess. Is this the right way to do this ? How can I display a choosen contact form in a node ?

Thanks

2

Your code will work when this patch is implemented:

Add a view builder for contact_form

| improve this answer | |
  • 1
    Right direction, but what you actually want to write is "Your code will no longer be needed because it will just work with that patch :)" – Berdir Nov 26 '15 at 20:40
  • I believe that patch should've gotten into 8.1.0, but it doesn't "just work" from what I can tell. I have the field set to "Rendered View" since that is the only formatter that is available aside from Label and Entity ID. That gives an error of Notice: Trying to get property of non-object in Drupal\views\Element\View::preRenderViewElement() (line 49 of ..../core/modules/views/src/Element/View.php). – nicholas.alipaz May 3 '16 at 23:54
  • 1
    @nicholas.alipaz, it is now planned for 8.2, in the meantime it is in drupal.org/project/contact_storage (and see Berdir's comment, you probably don't need any code) – 4k4 May 4 '16 at 8:38
  • +1 for contact_storage as the stop-gap solution before drupal core fixes it. I do like the other features of contact_storage too. A new display formatter is available for a contact form entity reference called rendered entity after the module is enabled. Thanks! – nicholas.alipaz May 4 '16 at 16:08

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.