Почему символы вставляются в мою ссылку PHP? - PullRequest
0 голосов
/ 05 ноября 2018

Я создал модуль, но ссылка не верная.

Мой сайт теперь показывает:

 /store/2?0=/cgv

Правильная ссылка должна быть:

 /store/2/cgv

Почему это не работает? где ошибка?
Что я должен изменить в приведенном ниже коде, чтобы получить ссылку?

<?php

namespace Drupal\commerce_agree_cgv\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 = "agree_cgv",
 *   label = @Translation("Agree CGV"),
 *   default_step = "review",
 * )
 */
class AgreeCGV extends CheckoutPaneBase implements CheckoutPaneInterface {

  /**
   * {@inheritdoc}
   */
  public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
    $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' => 800,
        ]),
      ],
    ];
    $link = Link::createFromRoute(
      $this->t('the general terms and conditions of business'),
      'entity.commerce_store.canonical',
      ['commerce_store' => $store_id, '/cgv'],
      $attributes
    )->toString();
    $pane_form['cgv'] = [
      '#type' => 'checkbox',
      '#default_value' => FALSE,
      '#title' => $this->t('I have read and accept @cgv.', ['@cgv' => $link]),
      '#required' => TRUE,
      '#weight' => $this->getWeight(),
    ];
    return $pane_form;
  }

}

1 Ответ

0 голосов
/ 07 ноября 2018

Поскольку $link построено неправильно:

$link = Link::createFromRoute(
  $this->t('the general terms and conditions of business'), 
  'entity.commerce_store.canonical', 
  ['commerce_store' => $store_id, '/cgv'], # -> this is wrong
  $attributes
)->toString();

$ route_parameters: (необязательно) Ассоциативный массив имен параметров и значения.

Вы не указали никакого имени для 2-х параметров маршрута, поэтому соответствующий ключ массива откат к первому доступному числовому индексу, то есть 0, что означает [ '/cgv' ], становится [ 0 => '/cgv' ], и вы не получаете ссылку ты ожидал

Я думаю (если я правильно понял вашу проблему), вам нужно в первую очередь определить, какой конкретный маршрут обрабатывает cgv для данного commerce_store, то есть с добавлением /cgv:

$route_collection = new RouteCollection();
$route = (new Route('/commerce_store/{commerce_store}/cgv'))
  ->addDefaults([
    '_controller' => $_controller,
    '_title_callback' => $_title_callback,
  ])
  ->setRequirement('commerce_store', '\d+')
  ->setRequirement('_entity_access', 'commerce_store.view');
$route_collection->add('entity.commerce_store.canonical.cgv', $route);

... чтобы вы могли создавать ссылки на основе этого конкретного маршрута:

$link = Link::createFromRoute(
  $this->t('the general terms and conditions of business'), 
  'entity.commerce_store.canonical.cgv',
  ['commerce_store' => $store_id],
  $attributes
)->toString();
...