php 在自定义模块中获取 URL 参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37675445/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:19:46  来源:igfitidea点击:

Get URL parameters inside custom module

phpdrupaldrupal-8

提问by zied123456

I've created a custom block like this:

我创建了一个这样的自定义块:

class HelloBlock extends BlockBase implements BlockPluginInterface{

  /**
   * {@inheritdoc}
   */
  public function build() {
    $config = $this->getConfiguration();
    $result = db_query('SELECT * FROM {test}');
    return array(
      '#theme' => 'world',
      '#test' => $result
    );
  }
}

And I now want to programmatically get some parameter from the URL.

我现在想以编程方式从 URL 获取一些参数。

For example:

例如:

If the URL is http://localhost/drup/hello/5569I want to get hold of the value 5569inside my module.

如果 URL 是http://localhost/drup/hello/5569我想获取5569我的模块中的值。

I have tried arg(1)and drupal_get_query_parameters()but I got this error messages:

我试过了arg(1)drupal_get_query_parameters()但我收到了以下错误消息:

Call to undefined function `Drupal\hello\Plugin\Block\arg()`

and

Call to undefined function `Drupal\hello\Plugin\Block\drupal_get_query_parameters()`

How can I get the parameters?

如何获取参数?

回答by Manish yadav

Use \Drupal\Core\Routing;:

使用\Drupal\Core\Routing;

$parameters = \Drupal::routeMatch()->getParameters();

The named parameters are available as

命名参数可用作

$value = \Drupal::routeMatch()->getParameter('slug_name_from_route');

Where 'slug_name_from_router' comes from your routing.yml path property

'slug_name_from_router' 来自你的 routing.yml 路径属性的地方

path: '/your/path/{slug_name_from_route}'

路径:'/你的/路径/{slug_name_from_route}'

If you want the raw parameter without any upcastingyou can get

如果你想要没有任何向上转换的原始参数,你可以得到

$value = \Drupal::routeMatch()->getRawParameter('slug_name_from_route');

回答by B.lakshman

I used to get the parameter value from URL (localhost/check/myform?mob=89886665)

我曾经从 URL (localhost/check/myform?mob=89886665) 获取参数值

$param = \Drupal::request()->query->all();

And applied in my select Query

并应用于我的选择查询

 $query = \Drupal::database()->select('profile_register', 'p1');
 $query->fields('p1');
 $query->condition('p1.mobileno', $edituseprof);
 $query->condition('publishstatus', 'no');
 $result = $query->execute()->fetchAll();

But on multiple parameter value, i am now successful(Ex:http://10.163.14.41/multisite/check/myform?mob=89886665&id=1)

但是在多个参数值上,我现在成功了(例如:http : //10.163.14.41/multisite/check/myform?mob=89886665&id=1 )

 $query = \Drupal::database()->select('profile_register', 'p1');
 $query->fields('p1');
 $query->condition('p1.mobileno', $edituseprof['mob']);
 $query->condition('p1.ids', $edituseprof['id']);
 $query->condition('publishstatus', 'no');
 $result = $query->execute()->fetchAll();

回答by Karthikeyan Manivasagam

arg() is deprecated in drupal 8, however we can get values like arg() function does in drupal 7 & 6

arg() 在 drupal 8 中被弃用,但是我们可以得到像 arg() 函数在 drupal 7 & 6 中所做的值

$path = \Drupal::request()->getpathInfo();
$arg  = explode('/',$path);
print_r($arg); exit(); 

The output would be parameters in url except basepath or (baseurl),

输出将是 url 中的参数,除了 basepath 或 (baseurl),

Array
(
   [0] => 
   [1] => node
   [2] => add
)

回答by Monal Soft

$route_match = \Drupal::service('current_route_match');
$abc = $route_match->getParameter('node'); //node is refrence to what you have written in you routing file i.e: 

in something.routing.yml
entity.node.somepath:
  path: '/some/{node}/path'

I have used {node} as arg(1). And I can access it by using *->getParameter('node');

我使用 {node} 作为 arg(1)。我可以使用 *->getParameter('node'); 访问它。

Hope this will work.

希望这会奏效。

回答by Tanvir Ahmad

To get query parameter form the url, you can us the following. If you have the url for example,

要从 url 获取查询参数,您可以使用以下方法。例如,如果您有网址,

domainname.com/page?uid=123&num=452

To get "uid"from the url, use..

要从url获取“uid”,请使用..

$uid = \Drupal::request()->query->get('uid');

To get "num"from the url, use..

要从url 中获取“num”,请使用..

$num = \Drupal::request()->query->get('num');

回答by Rahul Chauhan

If your url is like this below example

如果您的网址如下例所示

http://localhost/drupal/node/6666

Then you have to get the full url path by

然后你必须得到完整的 url 路径

$current_path = \Drupal::request()->getPathInfo();

then explode the path to get the arguments array.

然后分解路径以获取参数数组。

$path_args = explode('/', $current_path);

Another example if value passed by a key in url like below where id contains the value

另一个示例,如果值通过 url 中的键传递,如下所示,其中 id 包含值

http://localhost/drupal?id=123

You can get the id by given drupal request

您可以通过给定的 drupal 请求获取 ID

$id = \Drupal::request()->query->get('id');

回答by Umesh Patil

Here's the example of accessing URL parameters and passing them to a TWIG template, I am considering you have already created your module and required files and suppose "/test?fn=admin" is your URL

这是访问 URL 参数并将它们传递给 TWIG 模板的示例,我认为您已经创建了模块和所需文件,并假设“/test?fn=admin”是您的 URL

  1. In Your .module file implement hook_theme and define variables and template name (Make sure you replace "_" with "-" when creating the template file)

     function my_module_theme () {   
             return [
              'your_template_name' => [               
                 'variables' => [
                     'first_name'    => NULL,
                  ],   
             ]; 
           }
    
  1. 在您的 .module 文件中实现 hook_theme 并定义变量和模板名称(确保在创建模板文件时将“_”替换为“-”)

     function my_module_theme () {   
             return [
              'your_template_name' => [               
                 'variables' => [
                     'first_name'    => NULL,
                  ],   
             ]; 
           }
    

Now create your controller and put below code in it.

现在创建您的控制器并将以下代码放入其中。

 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"
     ];
   }

 }

Now in your TWIG file which should be "my-template.html.twig" you can access this parameter as,

现在在应该是“my-template.html.twig”的 TWIG 文件中,您可以访问此参数,

 <h3>First Name: {{ first_name }}</h3>

And its done. Hope this helps.

它完成了。希望这可以帮助。

回答by Joe Crombie

The Drupal docs are great on this: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes

Drupal 文档在这方面很棒:https: //www.drupal.org/docs/8/api/routing-system/parameters-in-routes

  1. define your path variable in yaml

    example.name:
      path: '/example/{name}'
      ...
    
  2. Add the variable in your method and use it

    <?php
    class ExampleController {  
      // ...
      public function content($name) {
        // Name is a string value.
        // Do something with $name.
      }
    }
    ?>
    
  1. 在 yaml 中定义路径变量

    example.name:
      path: '/example/{name}'
      ...
    
  2. 在您的方法中添加变量并使用它

    <?php
    class ExampleController {  
      // ...
      public function content($name) {
        // Name is a string value.
        // Do something with $name.
      }
    }
    ?>