Get original request info after a forward in Symfony 2 - symfony

I have created a custom Error 403 page using the access_denied_url parameter in security.yml: when showing the new page I want to tell people that the problem happened when trying to access page xxxxx.
$request->headers->get('referer') is empty.
/**
* #Route("/forbidden", name="error_403")
* #Template()
*/
public function error403Action(Request $request)
{
return array('referer' => $request->headers->get('referer'));
}
How can I get information about the original Request (the one that resulted in this forward)?

It got solved calling {{ app.request.server.get('PHP_SELF') }} directly in the Twig template.

Related

Configure persistent parameters for sonata admin menu urls

My sonata admin project should be accessable through {slug} url parameter:
/{slug}/admin/user/list
My routing configuration:
_sonata_admin:
resource: '.'
type: 'sonata_admin'
prefix: '/{slug}/admin'
Now when I access the admin I see this error:
An exception has been thrown during the rendering of a template ("Some
mandatory parameters are missing ("slug") to generate a URL for route
"admin_app_user_list".").
I tried configuring persistent parameters from my admin like this:
/**
* {#inheritdoc}
*/
protected function configurePersistentParameters(): array
{
return ['slug' => $this->getUser()->getUsername()];
}
But I still got the same error.
Upon checking when configurePersistentParameters is being called, in DefaultRouteGenerator::generateMenuUrl() I noticed that admin should have request object assigned:
if ($admin->hasRequest()) {
$parameters = array_merge($admin->getPersistentParameters(), $parameters);
}
If I remove the condition, the error is not displayed. So I guess when generating menu urls, the request object is not yet set.
Is there a way of passing route parameters when generating menu urls?

Laravel 5.3 Redefine "reset email" blade template

How to customize the path of the reset email blade template in Laravel 5.3?
The template used is: vendor/laravel/framework/src/Illuminate/Notifications/resources/views/email.blade.php
I'd like to build my own.
Also, how to change the text of this email predefined in: vendor/laravel/framework/src/Illuminate/Auth/Notifications/ResetPassword.php
public function toMail()
{
return (new MailMessage)
->line([
'You are receiving this email because we received a password reset request for your account.',
'Click the button below to reset your password:',
])
->action('Reset Password', url('password/reset', $this->token))
->line('If you did not request a password reset, no further action is required.');
}
To change template you should use artisan command php artisan vendor:publish it will create blade templates in your resources/views/vendor directory. To change text of email you should override the sendPasswordResetNotification method on your User model. This is described here https://laravel.com/docs/5.3/passwords in Reset Email Customization section.
You must add new method to your User model.
public function sendPasswordResetNotification($token)
{
$this->notify(new ResetPasswordNotification($token));
}
and use your own class for notification instead ResetPasswordNotification.
UPDATED: for #lewis4u request
Step by step instruction:
To create a new Notification class, you must use this command line php artisan make:notification MyResetPassword . It will make a new Notification Class 'MyResetPassword' at app/Notifications directory.
add use App\Notifications\MyResetPassword; to your User model
add new method to your User model.
public function sendPasswordResetNotification($token)
{
$this->notify(new MyResetPassword($token));
}
run php artisan command php artisan vendor:publish --tag=laravel-notifications After running this command, the mail notification templates will be located in the resources/views/vendor/notifications directory.
Edit your MyResetPassword class method toMail() if you want to. It's described here https://laravel.com/docs/5.3/notifications
Edit your email blade template if you want to. It's resources/views/vendor/notifications/email.blade.php
Bonus: Laracast video: https://laracasts.com/series/whats-new-in-laravel-5-3/episodes/9
PS: Thanks #Garric15 for suggestion about php artisan make:notification
I wanted to elaborate on a very helpful Eugen’s answer, but didn’t have enough reputation to leave a comment.
In case you like to have your own directory structure, you don’t have to use Blade templates published to views/vendor/notifications/... When you create a new Notification class and start building your MailMessage class, it has a view() method that you can use to override default views:
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
return (new MailMessage)
->view('emails.password_reset');
// resources/views/emails/password_reset.blade.php will be used instead.
}
In Addition to the above answer for Laravel 5.6, here it is easier to pass variables in an array to your custom email template.
/**
* Get the mail representation of the notification.
*
* #param mixed $notifiable
* #return \Illuminate\Notifications\Messages\MailMessage
*/
public function toMail($notifiable)
{
$url = url('/invoice/'.$this->invoice->id);
return (new MailMessage)
->subject('Invoice Paid')
->markdown('emails.password_reset', ['url' => $url]);
}
https://laravel.com/docs/5.6/notifications

Symfony Routing "_locale" parameter not accepted

I have a problem with the symfony routing.
For an multilanguage projekt I render a Twig template via a job queue for mailing. In this template is a link to a route that requires the "_locale" parameter with "de" or "en" for example. I use the function "{{ url('route', {'_locale': 'de'}) }}" to generate the url.
By rendering the template, I got the following error message:
[Twig_Error_Runtime]
An exception has been thrown during the rendering of a template ("Some mandatory parameters are missing ("_locale") to generate a URL for route "Route".") in "TemplatePath" at line 5.
Whats my mistake?
Thanks for help
When you are generating URL route, via CLI, the Symfony kernel is missing a HTTP Request, and a Routing->RequestContext.
Thats why, the URL generator cannot find _locale parameter.
To fix it, you must manually create a RequestContext, so, in your command:
$this->getContainer()->get('router')
->setContext(
(new RequestContext())
->setParameter('_locale', 'fr')
);
class BaseCommand extends ContainerAwareCommand
{
protected function getLocale()
{
return $this->getContainer()->get('translator')->getLocale();
}
protected function render($view, $data)
{
return $this->getContainer()->get('templating')->render($view, $data);
}
}
in command
class SomeCommand extends BaseCommand
{
...
$this->render($view, array_merge($data, ['_locale' => $this->getLocale()])
}
in view
{{url('any', {param: 'foo'}|merge(_locale is defined ? {'_locale': _locale } : {}))}}
It's necro time :)
I'm just guessing here, but there's a couple things you can try.
Can you set the locale in your command?
Set the locale for the translator bundle:
$this->getContainer()->get('translator')->setLocale('de');
Set the locale for this session:
$this->getContainer()->get('session')->setLocale('de);
Internationalized routing for Symfony 4.1 and higher
If this applies to you, try this:
url('route.de', {'_locale': 'de'}) }}"
Does your route have 'de' and 'en' set as a requirement?
/**
* Matches /route
* #Route(
* "/route/{_locale}",
* requirements={
* '_locale': 'en|de'
* },
* name="route"
* )
*/
It's an old question but this might help someone out.

Symfony - using twig trans filter on 404 page

I have a 404 error page set up through an event listener triggered by Kernel exceptions:
public function onKernelException(GetResponseForExceptionEvent $event)
{
if ($event->isMasterRequest()) {
$exception = $event->getException();
if ($exception instanceof NotFoundHttpException) {
$response = new Response();
$event->setResponse(
$response->setContent($this->templating->render(
'LandingPageBundle:Error:error404.html.twig',
['welcome_url' => $this->router->generate("welcome")]
))
);
}
}
}
kernel.kernel_exception_listener:
class: S\Project\LandingPageBundle\EventListener\KernelExceptionListener
arguments: [ "#router", "#logger", "#translator", #templating ]
tags:
- { name: kernel.event_listener, event: kernel.exception, method: onKernelException }
This works, but when I try to use the trans filter on the twig error404.html.twig template, it does nothing. My locale is being set in a cookie and read by an event listener to Kernel Requests, so I tried adding the following to onKernelException:
$request = $event->getRequest();
$locale = $request->cookies->get('_locale');
$request->setLocale($locale);
After that, including {{ app.request.locale }} in the template displayed the correct locale, however, the trans filter does not seem to be picking this up.
It seems like my problem may be related to Symfony 2.1 set locale and yet that question does not quite fit my exact problem, and I'm not sure what can be done to fix the problem. Ideally my kernel request listener could trigger before the onKernelException, so that it would properly set the locale beforehand, but currently it seems that the kernel request event is not triggered during a 404. I took a look at http://symfony.com/doc/current/components/http_kernel/introduction.html to better understand Symfony's request sequence, but I'm not really clear on the sequence that happens in a bad request, but it looks like in the case of an exception, it skips most of the request flow and goes straight to the response, and as I recall from http://symfony.com/doc/current/book/translation.html#handling-the-user-s-locale
"Setting the locale using $request->setLocale() in the controller is too late to affect the translator. Either set the locale via a listener (like above), the URL (see next) or call setLocale() directly on the translator service."
Is there a way to use the trans filter on a twig templated 404 page?
Try to inject the #translator and use its method setLocale.
['welcome_url' => $this->router->generate("welcome")]
And why did you create link in the listener? You should do it in the template using twig function called path.

SilverStripe framework only - how to handle 404

I'm using just the framework without the CMS module for the first time. When I visit the app via a URL that is not handled by a controller/action, I just get a page with the text "No URL rule was matched". This results from Director::handleRequest() not matching any controllers to the url segments... Or "Action 'ABC' isn't available on class XYZController."
I'd like to direct any unmached requests to a controller equivalent of a nice 404 page. What is the correct or best way to do this?
The error templates are only included in the CMS. The framework just returns the HTTP response code with a message in plain text.
I've just started on my own framework-only project too and this is my solution:
[routes.yml]
---
Name: rootroutes
---
Director:
rules:
'': 'MyController'
'$URLSegment': 'MyController'
[MyController]
class MyController extends Controller {
private static $url_handlers = array(
'$URLSegment' => 'handleAction',
);
public function index() {
return $this->httpError(404, "Not Found");
}
/**
* Creates custom error pages. This will look for a template with the
* name ErrorPage_$code (ie ErrorPage_404) or fall back to "ErrorPage".
*
* #param $code int
* #param $message string
*
* #return SS_HTTPResponse
**/
public function httpError($code, $message = null) {
// Check for theme with related error code template.
if(SSViewer::hasTemplate("ErrorPage_" . $code)) {
$this->template = "ErrorPage_" . $code;
} else if(SSViewer::hasTemplate("ErrorPage")) {
$this->template = "ErrorPage";
}
if($this->template) {
$this->response->setBody($this->render(array(
"Code" => $code,
"Message" => $message,
)));
$message =& $this->response;
}
return parent::httpError($code, $message);
}
}
[ErrorPage.ss]
<h1>$Code</h1>
<p>$Message</p>
You can also create more specific error templates using ErrorPage_404.ss, ErrorPage_500.ss etc.
Without updating the routes as previously mentioned, there's a module that I've been recently working on which will allow regular expression redirection mappings, hooking into a page not found (404). This has been designed to function with or without CMS present :)
https://github.com/nglasl/silverstripe-misdirection
It basically makes use of a request filter to process the current request/response, appropriately directing you towards any mappings that may have been defined.

Resources