首页 > 解决方案 > 如何在 Drupal 代码中显示商店的渲染实体?

问题描述

我为 Drupal 8 和 Drupal Commerce 创建了一个自定义模块。它用于在订单期间在购买漏斗中显示“接受销售条件”链接。

此链接显示一个带有页面呈现的模式窗口。

我在我的商店类型中创建了“条款和条件”显示模式。我希望链接在模式窗口中显示商店呈现的“条款和条件”实体。

所以我想制作实体商店而不是在模态链接中显示页面。

这个怎么做 ?

这是我的代码:

<?php

namespace Drupal\commerce_marketplace_terms_and_conditions\Plugin\Commerce\CheckoutPane;

use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneBase;
use Drupal\commerce_checkout\Plugin\Commerce\CheckoutPane\CheckoutPaneInterface;
use Drupal\Core\Link;
use Drupal\Core\Url;

/**
 * Provides the completion message pane.
 *
 * @CommerceCheckoutPane(
 *   id = "marketplace_terms_and_conditions",
 *   label = @Translation("Marketplace Terms and Conditions"),
 *   default_step = "review",
 * )
 */
class MarketplaceTermsAndConditions extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $store_name = $this->order->getStore()->getName();
    $store_id = $this->order->getStoreId();
    $pane_form['#attached']['library'][] = 'core/drupal.dialog.ajax';
    $attributes = [
      'attributes' => [
        'class' => 'use-ajax',
        'data-dialog-type' => 'modal',
        'data-dialog-options' => Json::encode([
          'width' => 'auto'
        ]),
      ],
    ];
    $link = Link::fromTextAndUrl(
      $this->t('terms and conditions of the store "@store_name"', ['@store_name' => $store_name]),
      Url::fromUri("internal:/store/$store_id/cgv", $attributes)
    )->toString();
    $pane_form['marketplace_terms_and_conditions'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @terms.', ['@terms' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

标签: phpdrupalmodal-dialogdrupal-8drupal-modules

解决方案


大多数情况下,EntityTypeManager 可用于加载和渲染实体。在上一篇文章中,有一些不同的方法可以做到这一点。请注意 entityManager 已被弃用,您可以使用 \Drupal::entityTypeManager()。

在这种情况下,实体类型是“commerce_store”。所以这样的事情可以在商务窗格中工作(将“默认”更改为您的显示模式的名称)。

  $entityMgr = \Drupal::entityTypeManager();
  $store = $entityMgr->getStorage("commerce_store")->load($storeId);

  if ($store) {
    $viewBuilder = $entityMgr->getViewBuilder('commerce_store');
    $pane_form['store'] = $viewBuilder->view($store, 'default');
  }

推荐阅读