How can I render the personal contact form in node twig template?

2.2k Views Asked by At

My website has many products posted by different people. In each node.html.twig, How can i show the personal contact form for each owner? I use the Twig Tweak module to render form. Suppose I have "author" variable (Drupal\user\Entity) for use.

I try in hook_preprocess_node:

function MY_thEME_preprocess_node(&$variables) {
$message = Drupal::entityTypeManager()->getStorage('contact_message')->create([
  'contact_form' => 'personal',
  'recipient' => $user->id(),
]);

$form = \Drupal\Core\Entity\EntityFormBuilder::getForm($message);
$form['#title'] = $this->t('Contact @username', ['@username' => $user->getDisplayName()]);
$form['#cache']['contexts'][] = 'user.permissions';
$variables['personal_form'] = drupal_render($form);
}
1

There are 1 best solutions below

0
On

You should use Renderer service instead of drupal_render() which is deprecated, e.g.

/**
 * Prepares variables for node templates.
 *
 * @see template_preprocess_node()
 */
function mymodule_preprocess_node(&$variables) {
  $message = Drupal::entityTypeManager()->getStorage('contact_message')->create([
    'contact_form' => 'personal',
    'recipient' => $user->id(),
  ]);

  $form = \Drupal\Core\Entity\EntityFormBuilder::getForm($message);
  $form['#title'] = $this->t('Contact @username', ['@username' => $user->getDisplayName()]);
  $form['#cache']['contexts'][] = 'user.permissions';
  $variables['personal_form'] = \Drupal::service('renderer')->renderRoot($form);
}