如何在节点树枝模板中呈现个人联系表单?

时间:2017-05-02 18:48:35

标签: drupal-8 drupal-contact-form

我的网站有很多不同的人发布的产品。在每个node.html.twig中,如何显示每个所有者的个人联系表单? 我使用Twig Tweak module来渲染表单。 假设我有"作者"变量(Drupal\user\Entity)供使用。

我尝试使用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 个答案:

答案 0 :(得分:0)

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);
}