How to get previous page route in Symfony? - symfony-1.4

I am looking for way to do this in 'right' symfony way.

There's a way to get the referer page from the $request variable. For example, if I was in myaction/mypage and click to myaction2/mypage2 by this getReferer() method I get 'http://myweb/myaction/mypage'.
If you are in an action method this can be done by
public function executeMyaction(sfWebRequest $request)
{
$previousUrl = $request->getReferer();
...
}
if you are somewhere else you can get the request by getting the conext
$previousUrl = $this->getContext()->getRequest()->getReferer();
For for sfWebRequest methods check the sfWebRequest API.
Note: this value could be inaccesible using proxy's

Related

How to pass query string with routes in laravel 5.4

I am using Laravel 5.4. I want to use query string like below:
tempsite.com/lessons?id=23
For getting this how routes are to be modified. It is possible to give route in the following way.
Route::get('lessons/id={id}', ['as' => 'lessons.index', 'uses' => 'Lessons\LessonController#index']);
But adding '?' is not getting for me. Please help us to provide a solution as early as possible.
If you are using resourceful controllers, your routes are all handled for you so you would simply put
Route::resource('lessons', 'Lessons\LessonController');
You can then use route model binding to bind the model instance which matches that particular ID.
Route::model('lesson', Lesson::class);
This would be done in your RouteServiceProvider.
I would also suggest having a good read of the following documentation on the laravel website https://laravel.com/docs/5.4/routing. It provides really good insight in to how routes work and how they should be structured.
Instead of tempsite.com/lessons?id=23
Pass it like this tempsite.com/lessons/23
and in the route
Route::get('lessons/{id}', ['as' => 'lessons.index', 'uses' => 'Lessons\LessonController#index']);
to get the id in your controller, write your function like this
public function index($id)
{
//do anything with $id from here
}
There is no need to define query string parameters in your routes. You can return query string parameters in your controller like so:
URL example: tempsite.com/lessons?id=23
public function lessons(Request $request)
{
$request->get('id'); // Using injection
Request::get('id'); // Using the request facade
request()->get('id'); // Using the helper function
}
You could even validate the parameter:
public function lessons(Request $request)
{
$this->validate($request, ['id' => 'required|integer']);
}
Note: If you want to make the URL not accessible if the ID is omitted, see #DarkseidNG answer.
I was able to inform laravel to accept query stringed requests on my route by affixing the url with a forward slash, like so
// web.php
Route::get('/path/', "Controller#action");
With the above, mysite/path?foo=bar&name=john does not throw 404 errors.

How To Call a Common function to Every (Twig) Symfony2

Hi I have a common function to get a Client Name dynamicaly. Now I want to call that function to every view (Twig). I am following it like this:
//My controler
public function getSchoolNameAction(){
$session = new Session();
$dm = $this->getDocumentManager();
$commonFunction = new CommonFunctions();
return $schoolName= $commonFunction->schoolName($dm,$session);
}
//My View (search.html.twig)
{% render controller('EduAccountBundle:Ledger:getSchoolName') %}
But its showing an error that :
he controller must return a response (null given). I need to make it for every view. Please guide me how to fix this
Don't define a controller as a service, controllers should be used only to take a request and to produce a response (you're just returning a value, that isn't acceptable for Symfony logic)
Unless you want to return a rendered template (or produce a valid response, such like a json response) to put where you're calling the common action (you could do that of course), I will recommend to write a custom twig extension

Symfony2 Get array from URL via POST

I send some data by POST.
For example: http://.../?tag[]=1&tag[]=2
I cant receive tag varible in controller, I tried to do something like this:
$this->get('request')->get('tag');
But I receive null.
Whats wrong?
If you are sending data as you mentioned via URL, it is a GET request.
public function exampleAction(Request $request)
{
$tagPost=$request->request->get('tag'); //from $_POST[]
$tagGet=$request->query->get('tag'); //from $_GET[]
var_dump($tagPost,$tagGet);
}
try:
$this->get('request')->request->get('tag');
instead of:
$this->get('request')->get('tag');
EDIT: IF you http method is GET (instead of POST), you can try with:
$this->get('request')->query->get('tag');
Check here for further detail
hope this help

How to fetch value from url in silverstripe

I want to print value 5 on the ss page.
www.xyz.com?a=5.
How to fetch url data in silverstripe? Any help is accepeted.
In your controller that your Silverstripe template is for, you can retrieve "GET" (aka. query string) by returning the result of $this->getRequest()->getVar('a') in a function on your controller.
It is good practice to use $this->getRequest()->getVar('a') over $_GET['a'] as SilverStripe will automatically sanitise the string.
When your code is not in the controller (so you can't make use of $this->getRequest()), you can request the current controller by using Controller::curr() which will make the complete call for getting a single var:
Controller::curr()->getRequest()->getVar('a')
If you want to get all "GET" variables, just call getVars() instead..
Also, you can access "POST" variables in a similar calling postVar('a') or postVars() instead. If you want to get the value from both "POST" or "GET", you can call requestVar('a') or requestVars().
Anyway, here is a basic mock-up of a controller using a function on the controller that is accessible in the template.
Controller
class TestPage_Controller extends Page_Controller
{
public function init()
{
parent::init();
}
public function MySpecialProperty()
{
return $this->getRequest()->getVar('a');
}
}
Template
<p> $MySpecialProperty </p>

Symfony2 - Authentication lost after redirection

I've been experiencing an issue with my SF2 application today.
I want the user to be automatically authenticated after submiting a valid subscription form.
So basically in my controller here's what I do:
if ($form->isValid()) {
$customer = $form->getData();
try {
$customer = $this->get('my.service.manager.customer')->customerSubscribe($customer);
} catch (APIClientException $e) {
$error = $e->getErrors();
...
}
if ($customer && !isset($error)) {
// connect customer
$token = new UsernamePasswordToken($customer, null, 'api_auth', array('ROLE_USER'));
$this->get('security.context')->setToken($token);
...
}
return new RedirectResponse($this->generateUrl('MyBundle_index'));
}
The two lines below the 'connect customer' comment actually seem to authenticate the user fine.
The problem being when I redirect to another page with RedirectResponse, then the authentication is lost.
I've tried a call to
$this->container->get('security.context')->isGranted('ROLE_USER')
which returns true just before the call to RedirectResponse, and false in my other controller where the response is being redirected.
At this point I'm a bit confused about what I'm doing wrong. Any ideas appreciated.
Btw, I'm using Symfony2.1
I've noticed this happens when you redirect more than once at a time. Does the controller for the MyBundle_index route return another redirect? If so, I think that's your answer.
Otherwise, maybe try using forwards? Instead of:
return new RedirectResponse($this->generateUrl('MyBundle_index'));
...just forward to whatever controller/action is defined for that route:
return $this->forward("SomeBundle:Default:index");
The URL that the user ends up with in their address bar might not be what you're expecting (it won't change from the one they requested originally), but you can probably fiddle with that to get it to your liking.
Ok I solved it like so:
$token = new UsernamePasswordToken($customer->getEmail(), null, 'api_auth', array('ROLE_USER'));
Apparently I needed to pass the customer id (in that case the email) as the first argument of UsernamePasswordToken, instead of the entire customer object. I'm not sure why since my entity Customer has a _toString method implemented, but at least it works fine like that.

Resources