Get URL parameters inside custom module - php

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.
For example:
If the URL is http://localhost/drup/hello/5569 I want to get hold of the value 5569 inside my module.
I have tried arg(1) and drupal_get_query_parameters() but I got this error messages:
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?

Use \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
path: '/your/path/{slug_name_from_route}'
If you want the raw parameter without any upcasting you can get
$value = \Drupal::routeMatch()->getRawParameter('slug_name_from_route');

I used to get the parameter value from 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)
$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();

arg() is deprecated in drupal 8, however we can get values like arg() function does in 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),
Array
(
[0] =>
[1] => node
[2] => add
)

To get query parameter form the url, you can us the following.
If you have the url for example,
domainname.com/page?uid=123&num=452
To get "uid" from the url, use..
$uid = \Drupal::request()->query->get('uid');
To get "num" from the url, use..
$num = \Drupal::request()->query->get('num');

$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');
Hope this will work.

If your url is like this below example
http://localhost/drupal/node/6666
Then you have to get the full url path by
$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
http://localhost/drupal?id=123
You can get the id by given drupal request
$id = \Drupal::request()->query->get('id');

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
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,
],
];
}
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,
<h3>First Name: {{ first_name }}</h3>
And its done.
Hope this helps.

The Drupal docs are great on this: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes
define your path variable in yaml
example.name:
path: '/example/{name}'
...
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.
}
}
?>

Related

How to pass URL parameter into a PHP file?

everyone.
I have created very basic router in PHP and now I am stuck.
The user can navigate to different URLs and pass parameters that can be used to display data for example to get data from an array.
However I am stuck, I do not know how to pass these url parameters so they can be used inside a file.
For example this route
"/user/:id" -> If user navigates to /user/1 -> This executes a callback function and he receives data from an array.
However when the url doesn't have callback function but has a name of a file, the router will load a file, for example the user page.
Router::get("/user/:username", "user.php");
So my question is How can I get the "username" from the route and pass it into the user.php file ?
I have tried using $_GET['username'], however that doesn't work as the url doesn't have ? inside of it.
This is my code
<?php
class Router{
public static $routes = [];
public static function get($route, $callback){
self::$routes[] = [
'route' => $route,
'callback' => $callback,
'method' => 'GET'
];
}
public static function resolve(){
$path = $_SERVER['REQUEST_URI'];
$httpMethod = $_SERVER['REQUEST_METHOD'];
$methodMatch = false;
$routeMatch = false;
foreach(self::$routes as $route){
// convert urls like '/users/:uid/posts/:pid' to regular expression
$pattern = "#^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['route'])) . "$#D";
$matches = Array();
// check if the current request matches the expression
if(preg_match($pattern, $path, $matches) && $httpMethod === $route['method']) {
$routeMatch = true;
// remove the first match
array_shift($matches);
// call the callback with the matched positions as params
if(is_callable($route['callback'])){
call_user_func_array($route['callback'], $matches);
}else{
self::render($route['callback']);
}
}
}
if(!$routeMatch){
self::notFound();
}
}
public static function render($file, $viewsFolder='./views/'){
include($viewsFolder . $file);
}
public static function notFound(){
http_response_code(400);
include('./views/404.php');
exit();
}
}
Router::get("/", "home.php");
Router::get("/user/:id", function($val1) {
$data = array(
"Nicole",
"Sarah",
"Jinx",
"Sarai"
);
echo $data[$val1] ?? "No data";
});
Router::get("/user/:username", "user.php");
Router::get("/user/profile/:id", "admin.php");
Router::resolve();
?>
You could pass $matches to the render() method as second optional parameter, and that's it. As well as these variables are accessible in the method scope, they are accessible in all the files included/required from this scope. I.e.:
self::render($route['callback'], $matches);
and in the included file:
print_r($matches);
UPD: In order to IDE not highlighting "unknown" variable, you can add a phpdoc-block somewhere in the included file, like this:
/** #var array $matches */

Pass optional arrgument Laravel 5.8, cron job

protected $signature = 'do_command {import=false}';
public function handle(){
$import= $this->argument('import');
if($import){
// do something else
}
}
and I am using it in the controller and NOT only:
$command = 'do_command';
$option = null;
if($import){
$option = 'import';
}
Artisan::call($command, [$option]);
The problem is, it doesn't matter, if $import in the controller is true/false, if statement is always executed and $this->argument('import') is always true in handle method, even if I call Artisan::call($command) without second argument.
You are defining the default value of import as false, which would be a string. Therefore, the if condition in your command will always be true:
if ($import) {
//
}
What you could do is change the signature to have the import option as optional.
protected $signature = 'command:name {import?}';
Then in your controller:
Artisan::call($command, [
'import' => $import,
]);
First define the options as parameters.
class GenerateApiToken extends Command
{
protected $signature = "apitoken:generate
{--id= : A description of the option}
{--value= : A description of the option}
";
public function handle()
{
$id = $this->option('id');
$value = $this->option('value');
...
Then grab them using $this->option()
To use them in a call from the application:
Artisan::call('apitoken:generate', ['id' => $id]);
Edit: I think the reason yours doesn't work is because the array you're passing the command in the second parameter of ::call() is not an associative array with the keynames representing options.

CodeIgniter - Optional parameters

I'm building my first CodeIgniter application and I need to make URLs like follows:
controllername/{uf}/{city}
Example: /rj/rio-de-janeiro
This example should give me 2 parameters: $uf ('rj') and $city ('rio-de-janeiro')
Another URL possible is:
controllername/{uf}/{page}
Example: /rj/3
This example should give me 2 parameters: $uf ('rj') and $page (3)
In other words, the parameters "city" and "page" are optionals.
I can't pass something like '/uf/city/page'. I need always or 'city' OR 'page'.
But I don't know how to configure these routes in CodeIgniter configuration to point to same method (or even to different methods).
I've found the correct result:
$route['controllername/(:any)/(:any)/(:num)'] = 'ddd/index/$1/$2/$3';
$route['controllername/(:any)/(:num)'] = 'ddd/index/$1/null/$2'; // try 'null' or '0' (zero)
$route['controllername/(:any)'] = 'ddd/index/$1';
The Index method (inside "ControllerName") should be:
public function Index($uf = '', $slug = '', $pag = 0)
{
// some code...
if (intval($pag) > 0)
{
// pagination
}
if (!empty($slug))
{
// slug manipulation
}
}
Hope it helps someone.
Thank you all.
public function my_test_function($not_optional_param, $optional_param = NULL)
{
//do your stuff here
}
have you tried this?
For example, let’s say you have a URI like this:
example.com/index.php/mycontroller/myfunction/hello/world
example.com/index.php/mycontroller/myfunction/hello
Your method will be passed URI segments 3 and 4 (“hello” and “world”):
class MyController extends CI_Controller {
public function myFunction($notOptional, $optional = NULL)
{
echo $notOptional; // will return 'hello'.
echo $optional; // will return 'world' using the 1st URI and 'NULL' using the 2nd.
}
}
Reference: https://codeigniter.com/user_guide/general/controllers.html

Slim PHP and GET Parameters

I'm using Slim PHP as a framework for a RESTful API.
How do I grab GET params from the URL in Slim PHP?
For example, if I wanted to use the following:
http://api.example.com/dataset/schools?zip=99999&radius=5
You can do this very easily within the Slim framework, you can use:
$paramValue = $app->request()->params('paramName');
$app here is a Slim instance.
Or if you want to be more specific
//GET parameter
$paramValue = $app->request()->get('paramName');
//POST parameter
$paramValue = $app->request()->post('paramName');
You would use it like so in a specific route
$app->get('/route', function () use ($app) {
$paramValue = $app->request()->params('paramName');
});
You can read the documentation on the request object
http://docs.slimframework.com/request/variables/
As of Slim v3:
$app->get('/route', function ($request, $response, $args) {
$paramValue = $request->params(''); // equal to $_REQUEST
$paramValue = $request->post(''); // equal to $_POST
$paramValue = $request->get(''); // equal to $_GET
// ...
return $response;
});
For Slim 3/4 you need to use the method getQueryParams() on the PSR 7 Request object.
Citing Slim 3 / Slim 4 documentation:
You can get the query parameters as an associative array on the
Request object using getQueryParams().
I fixed my api to receive a json body OR url parameter like this.
$data = json_decode($request->getBody()) ?: $request->params();
This might not suit everyone but it worked for me.
Slim 3
$request->getQueryParam('page')
or
$app->request->getQueryParam('page')
IF YOU WANT TO GET PARAMS WITH PARAM NAME
$value = $app->request->params('key');
The params() method will first search PUT variables, then POST variables, then GET variables. If no variables are found, null is returned. If you only want to search for a specific type of variable, you can use these methods instead:
//--- GET variable
$paramValue = $app->request->get('paramName');
//--- POST variable
$paramValue = $app->request->post('paramName');
//--- PUT variable
$paramValue = $app->request->put('paramName');
IF YOU WANT TO GET ALL PARAMETERS FROM REQUEST WITHOUT SPECIFYING PARAM NAME,
YOU CAN GET ALL OF THEM INTO ARRAY IN FORMAT KEY => VALUE
$data = json_decode( $app->request->getBody() ) ?: $app->request->params();
$data will be an array that contains all fields from request as below
$data = array(
'key' => 'value',
'key' => 'value',
//...
);
Hope it helps you!
Use $id = $request->getAttribute('id'); //where id is the name of the param
In Slim 3.0 the following also works:
routes.php
require_once 'user.php';
$app->get('/user/create', '\UserController:create');
user.php
class UserController
{
public function create($request, $response, array $args)
{
$username = $request->getParam('username'));
$password = $request->getParam('password'));
// ...
}
}
Not sure much about Slim PHP, but if you want to access the parameters from a URL then you should use the:
$_SERVER['QUERY_STRING']
You'll find a bunch of blog posts on Google to solve this. You can also use the PHP function parse_url.
Inside your api controller function write the following code of line:
public function your_api_function_name(Request $request, Response $response)
{
$data = $request->getQueryParams();
$zip = $data['zip'];
$radius = $data['radius'];
}
The variable $data contains all the query parameters.
Probably obvious to most, but just in case, building on vip's answer concerning Slim 3, you can use something like the following to get the values for the parameters.
$logger = $this->getService('logger');
$params = $request->getQueryParams();
if ($params) {
foreach ($params as $key => $param) {
if (is_array($param)) {
foreach ($param as $value) {
$logger->info("param[" . $key . "] = " . $value);
}
}
else {
$logger->info("param[" . $key . "] = " . $param);
}
}
}

Accessing object properties of type array dynamically

I am building a Language class for internationalization, and I would like to access the properties dynamically (giving the string name), but I don't know how to do it when dealing with arrays (this is just an example):
class Language {
public static $languages_cache = array();
public $index_header_title;
public $index = array(
"header" => array(
"title" => NULL
)
);
}
Now I add languages like this:
Language::$languages_cache["en"] = new Language();
Language::$languages_cache["en"]->index_header_title = "Welcome!"; //setting variable
Language::$languages_cache["en"]->index["header"]["title"] = "Welcome!"; //setting array
Function for accessing members dynamically:
function _($member, $lang)
{
if (!property_exists('Language', $member))
return "";
return Language::$languages_cache[$lang]->$member;
}
So, outputting members:
echo _('index_header_title', "en"); //works
echo _('index["header"]["title"]', "en"); //does not work
I would need a way for accessing arrays dynamically.. for public and private via __set() function.
Thank you!
You could try using a separator flag so that you can parse the array path. The only problem is you are mixing you properties and arrays so that might complicate things.
You would call your function like this:
echo _('index.header.title', "en");
And your function would parse the path and return the correct value. Take a look at the array helper in Kohana 3.0. It has the exact function that you want. http://kohanaframework.org/guide/api/Arr#path

Categories