Answers:
从更改记录:
$name = $_POST['name']; // form param
变成
$name = \Drupal::request()->request->get('name'); // form param
顺带提及,对于GET
vars,您可以使用:
$query = \Drupal::request()->query->get('name');
\Drupal::request()->request->all()
在控制器中,获取带有类型提示参数的请求Request $request
:
<?php
namespace Drupal\mymodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
class ExampleController extends ControllerBase {
/**
* Controller to return a POST or a GET parameter.
*/
public function action(Request $request) {
// get your POST parameter
$foo = $request->request->get('foo');
// or get your GET parameter
$foo = $request->query->get('foo');
return ['#markup' => $foo];
}
}
更多信息https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes
将RequestStack
注入您的控制器。
当前请求包含query
属性,该属性又包含GET参数。request
包含POST参数。
<?php
namespace Drupal\example_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* An example controller.
*/
class ExampleController extends ControllerBase {
/**
* @var Symfony\Component\HttpFoundation\RequestStack
*/
private $requestStack;
/**
* Constructor.
*
* @param Symfony\Component\HttpFoundation\RequestStack $request_stack
*/
public function __construct(RequestStack $request_stack) {
$this->requestStack = $request_stack;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('request_stack')
);
}
/**
* {@inheritdoc}
*/
public function action() {
// Get your GET parameter here.
$this->requestStack->getCurrentRequest()->query->get('foo');
}
}
这是访问URL参数并将其传递给TWIG模板的示例,我考虑到您已经创建了模块和必需的文件,并假设“ / test?fn = admin”是您的URL
function my_module_theme () { return [ 'your_template_name' => [ 'variables' => [ 'first_name' => NULL, ], ]; }
现在创建您的控制器,并将下面的代码放入其中。
namespace Drupal\my_module\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
class MyModule extends ControllerBase {
public function content(Request $request) {
return [
'#theme' => 'my_template',
'#first_name' => $request->query->get('fn'), //This is because the parameters are in $_GET, if you are accessing from $_POST then use "request" instead "query"
];
}
}
现在,在您的TWIG文件(应为“ my-template.html.twig”)中,您可以通过以下方式访问此参数:
<h3>First Name: {{ first_name }}</h3>
它完成了。希望这可以帮助。