我试图重写商业产品视图的实体视图控制器,以便根据特定条件重定向用户。
我正试图通过RouteSubscriber::alterRoutes实现来完成这一任务。
class RouteSubscriber extends RouteSubscriberBase {
/**
* {@inheritdoc}
*/
protected function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('entity.commerce_product.canonical')) {
$route->addDefaults(['_controller' => '\Drupal\mymodule\Controller\ProductViewController::view']);
}
}
}确认了我的自定义控制器,但我得到了以下错误:
控制器"Drupal\mymodule\Controller\ProductViewController::view()“需要为"$_entity”参数提供一个值。要么参数为空且没有提供空值,要么没有提供默认值,或者因为在这个参数之后有一个非可选的参数。在Symfony\Component\HttpKernel\Controller\ArgumentResolver->getArguments()中( /var/www/html/vendor/symfony/http-kernel/Controller/ArgumentResolver.php).的第78行)
我的Drupal\Core\Entity\Controller\EntityViewController.扩展了ProductViewController
class ProductViewController extends EntityViewController {
public function view(EntityInterface $_entity, $view_mode = 'full')
{
return parent::view($_entity, $view_mode);
}
}有人能告诉我需要添加哪些额外的路由上下文参数才能正常工作吗?
发布于 2021-02-11 00:49:46
我认为,您可能会在alterRoutes方法中取消一些以您现在的方式执行的操作。(但是,在查看路线:addDefaults()之后,我无法知道是否或为什么会发生这种情况。)
我也在为媒体实体的路线做同样的事。我的alterRoutes方法有点不同--我正在使用路线:setDefault()。
public function alterRoutes(RouteCollection $collection) {
if ($route = $collection->get('entity.media.canonical')) {
$route->setDefault('_controller', '\Drupal\my_module\Controller\MyController::view');
}
}此外,控制器方法中的变量名很重要--它们必须与路由定义中的变量名匹配。请参阅在路由中使用参数的文档
在大多数PHP代码中,变量的名称并不重要,但在这里是这样的:方法参数的the名称必须与段塞匹配。相反,如果方法参数名与段塞的名称匹配,则参数将被传递进来,而不管参数的顺序如何。
发布于 2021-02-11 15:12:12
我想出来了。问题是争论的名字。一旦我在控制器::view方法中将$_entity更改为$commerce_product,它就开始工作了。
class ProductViewController extends EntityViewController {
public function view(EntityInterface $commerce_product, $view_mode = 'full')
{
return parent::view($commerce_product, $view_mode);
}
}我通过寻找扩展EntityViewController的其他类来解决这个问题,我发现NodeViewController和变量名是唯一有意义的区别。
这种特定的变量命名约定是有点非常规的imxp,但我相信我已经在这个Drupal 8中看到了其他地方。
不管怎样,谢谢你的帮助@sonfd,我希望这能帮助到其他人。
https://drupal.stackexchange.com/questions/300119
复制相似问题