I am working on symfony 2.2 and I have an issue, when I try to delete a get variable such as message in this url : myurl?message=mymessage
It doesn't work.
public function myfunction1() {
....
return $this->redirect($this->generateUrl('_admin_credit', array("message" => $message))); // generate the url : myurl?message=mymessage
}
/**
* #Route("/credit", name="_admin_credit")
*/
public function getCreditAction($) {
$request = $this->getRequest();
$message = $request->query->get('message'); // this works
$request->query->remove('message'); // this work in the function but do not change the url
return $this->render('MyBundle:Admin:credit.html.twig', array(
'message' => $message
)); // still the same url : myurl?message=mymessage
}
$request->query->remove('message'); will remove the paramter from the ParameterBag only.
If you want to remove it from the URL you have to redirect to an URL without the parameter.
In Addition, if you want to keep the value of message, you can use a Flash Message to store it between two requests. This means: you can get the parameter, store it, redirect to another URL and recall the value once from the session.
Related
I have a scenario where I need to perform some redirection of a not found url
http://localhost/drupal9/node/1/search
the word search is added though a plugin I am using and it is a front-end route not a backend so upon refreshing this url I get Not Found which totally makes sense what I need to do is remove the word search from the URL and redirect to,
http://localhost/drupal9/node/1/
as search is a common word and can be used in other content type I first need to check whether the URL is of my custom content type. let me show you a piece of implementation I already have.
function [module]_preprocess_page(&$variables) {
$query = \Drupal::entityQuery('node')
->condition('type', [module]);
$nids = $query->execute();
if(array_search(2,$nids)){
echo "yes";
}
}
so over here what I am doing is grabbing all the nodes with my content type and grabbing the Nid from URI and matching them and this does work but there is another problem with this.
In the page properties we have an option of ALias so if the user uses a custom alias, then I dont get the Nid in the URI anymore so this logic breaks,
the question may seem a bit tricky but the requirement is simple.I am looking for a unified solution to parse the URL into some drupal API and simply getting back the content type name.The Url may contain a custom alias or a Nid
You can create an EventSubscriber subscribing the event kernel.request to handle the case of URL <node URL>/search.
For detailed steps to create an EventSubscriber, you can see here.
And below is what you need to put in your EventSubscriber class:
RequestSubscriber.php
<?php
namespace Drupal\test\EventSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\KernelEvents;
/**
* Class RequestSubscriber.
*/
class RequestSubscriber implements EventSubscriberInterface {
/**
* {#inheritdoc}
*/
public static function getSubscribedEvents() {
return [
KernelEvents::REQUEST => 'onKernelRequest',
];
}
public function onKernelRequest($event) {
$uri = $event->getRequest()->getRequestUri(); // get URI
if (preg_match('/(.*)\/search$/', $uri, $matches)) { // check if URI has form '<something>/search'
$alias = $matches[1];
$path = \Drupal::service('path_alias.manager')->getPathByAlias($alias); // try to get URL from alias '<something>'
if (preg_match('/node\/(\d+)/', $path, $matches)) { // if it is a node URL
$node = \Drupal\node\Entity\Node::load($matches[1]);
$content_type = $node->getType();
//... some logic you need
}
}
}
}
I want to add an extra variable "type"
so i do multiple root in annotation.
then i try this
/**
* #Route("/Theme/{id}/{type}", name="theme_show")
* #Route("/Theme/{id}", name="theme_show")
*/
public function show($id, $type = null, Request $request, ObjectManager $manager){
and the return
return $this->render('blog/show.html.twig', [
'type' => $type,
]);
and this my button to go at this function
<a class="btn btn-dark btn-block" href="{{ path('theme_show', {'id' : theme.id, 'type' : 'question'})}}" role="button">Question</a>
and this my url when i try to change page
http://127.0.0.1:8000/Theme/5?type=question
but when i dump the content of type in this url i find = null
i also try with a unique rooting annotation
/**
* #Route("/Theme/{id}/{type}", name="theme_show")
*/
public function show($id, $type, Request $request, ObjectManager $manager){
and i have this error
No route found for "GET /Theme/5" (from "http://127.0.0.1:8000/Theme/5?type=idee")
The URL you are using doesn't match the route.
Your URL
http://127.0.0.1:8000/Theme/5?type=question
Correct URL
http://127.0.0.1:8000/Theme/5/question
Route
* #Route("/Theme/{id}/{type}", name="theme_show")
If you want to use query parameters as you do in your URL. You'll have to retrieve it from the request.
$type = $request->query->get('type');
Next, you have two routes with the same name. I'm pretty sure this is not valid even if it is used for the same method. If you run php bin/console debug:router, you'll see that only the latest is showing up.
So either you change the name of one of the routes and use your pattern /Theme/{id}/{type} or you use query parameter like explained and get rid of the route with 'type'.
I use Datatables on fronted to send GET parameters to my Silex application.
Datatables send GET parameters of that type:
champs_societes%5B%5D=naf&zone-geographique=ville&effectif%5B%5D=eff_1a9&effectif%5B%5D=eff_10a19&effectif
%5B%5D=eff_20a49&effectif%5B%5D=eff_plus5000&ca%5B%5D=10k-50k&ca%5B%5D=50k-100k&ca%5B%5D=1kk-2kk&ca%5B
%5D=2kk-5kk&champs_societes%5B%5D=capital_int&fondation%5Bmin%5D=&fondation%5Bmax%5D=&champs_societes
%5B%5D=siren&champs_societes%5B%5D=siret&champs_societes%5B%5D=nature&nature%5B%5D=Etablissement&champs_societes
%5B%5D=formejur&champs_societes%5B%5D=emailg&champs_contacts%5B%5D=emailn&ac_formejur=Artisan-Commer
%C3%A7ant%2CBanque+Populaire%2FLoi+Mars+1917%2CCoop.+%C3%80+Responsabilit%C3%A9+Limit%C3%A9e&ac_naf=0113Z
%2C0121Z%2C0126Z%2C0130Z&ac_departements=14%2C50%2C61%2C68%2C03&ac_villes=77330%2C77680%2C77340&ac_fonction
=Assistant%2CCharg%C3%A9+D'Affaires%2CContr%C3%B4leur+De+Gestion%2CDirecteur+%2F+Responsable
I there a way to genereate a clean URL from this chain ? Ideally by using the Symfony/Silex routing.
Thanks for help
EDIT
I get the GET params above with Request:
$app->post('/ajax/formprocess', function (Request $request) use ($app) {
$df = new Filtres( $request->request->get('dataForm') );
$filtroAdd = $df->getRequest();
I would try with Request class first
Request class from HttpFoundation component (default in Symfony, not sure about Silex as I never used it)
/**
* #param \Symfony\Component\HttpFoundation\Request $request
*/
public function someAction(Request $request)
{
$request->getSchemeAndHttpHost();
$request->getBasePath();
$request->getQueryString(); // this will be the most helpful in your case
// access what you need and build normalized url
}
You should be able to build clean normalized url
Edit, solution for parsing query parameter string to array
$queryParameters = 'query parameters as string to be parsed';
$output = [];
parse_str($queryParameters, $queryParameters);
print_r($queryParameters);
http://php.net/manual/en/function.parse-str.php
I discovering symfony3, but im stuck at getting the parameters passed with a link from an action.
In my twig file, im redirecting the user to an action:
<td>go to</td>
And im my action, i'm trying to get the id with:
/**
* #Route("/AfficheDetail", name="esprit_park_affiche")
*/
public function afficheAction()
{
$id = $this->getParameter("id");
return $this->render("#EspritPark/Voiture/affiche.html.twig", array("id" => $id));
}
but each time i get: The parameter "id" must be defined.
like the getParameter isnt returning anything.
I even tried with:
$id = $this->get("request")->get("id");
but i get: You have requested a non-existent service "request". Did you mean one of these: "monolog.logger.request", "request_stack", "router.request_context", "data_collector.request"?
The getParameter() method from the base Controller class is looking up parameters from the service container.
I would make the parameters part of your route. You can then retrieve the values through the action method's parameters:
/**
* #Route("/AfficheDetail/{id}/{serie}/{dateMise}/{marque}", name="esprit_park_affiche")
*/
public function afficheAction($id, $serie, $dateMise, $marque)
{
// ...
}
If you do not add them to the route pattern, they will be accessible through the URL parameters (the current request will be injected automatically if you type hint an argument with the Request class):
public function afficheAction(Request $request)
{
$id = $request->query->get('id');
$serie = $request->query->get('serie');
$dateMise = $request->query->get('dateMise');
$marque = $request->query->get('marque');
// ...
}
When I do a forward() in a controller, I lose my route and route_parameters.
When I have ParentAction, that does a forward to ChildAction. In Childaction I do return $this->render('myTemplate.html.twig', array()); then the request attributes get nested!
So when the template gets rendered, instead of $request['attributes']['_route_parameters'] I get $request['attributes']['request']['attributes']['_route_parameters'].
Although in ChildAction, when I do a $this->getRequest(); the hierarchie is normal.
Is this a bug, or am I doing something wrong?
The reason is that symfony doesn't assume you have the same route parameters.
So when you forward you need to re-supply the route parameters required by the new route even if they are the same.
(Incidentally you must also provide any query parameters for the new route.)
public function indexAction($param)
{
return $this->forward(
'AppBundle\\Controller\\DefaultController::otherAction',
array("someOtherParam" => $param),
$request->query->all() // Causes query string params to be copied
);
}
// This route has a different parameter.
public function otherAction($someOtherParam) ...
A possible solution would be to pass your Request as second parameter when forwarding.
$response = $this->forward('MyBundle:MyController:myAction', array('request' => $request));
Also, as forward is just a shortcut for core Symfony2 functionality, this may probably help.
In my case following code helped:
$subRequest = $this->container->get('request')->duplicate(
array(),
null,
array('topicId' => $topicId,'_controller' => 'SomeBundle:Topic:close'));
return $this->container->get('http_kernel')
->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
"Topic" is TopicController and "close" is closeAction