Symfony2 Fos Rest showing url , giving 500 in logs - php

app/console router:debug shows
get_test_helloworld GET /test/helloworld.{_format}
but on hitting this url, nothing is displayed and in logs i get
[2013-06-08 02:38:44] request.ERROR: Symfony\Component\HttpKernel\Exception\NotFoundHttpException:
No route found for "GET /test/helloworld" (uncaught exception)
at /home/user/Code/app/cache/prod/classes.php line 4261 [] []
My TestController
<?php
namespace User\Bundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use FOS\RestBundle\View\View;
use FOS\RestBundle\Response\Codes;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
class TestController extends Controller
{
public function getTestHelloworldAction()
{
var_dump('hello world');die;
}
}
I am using FosRest bundle and routing.yml have
test:
type: rest
resource: User\Bundle\Controller\TestController
Stuck here from long time now. Any ideas where is this going wrong?

Clear the cache and restart server and php. Hope this helps.

The problem that you don't have /test/helloworld route, you have only test/helloworld.html cause for format, html is the default value, id you doesn't specify otherwise.
If you want to test for AJAX calls (eg format with json ) AND normal request then leave it like this, but if you will use only with html format, remove the .{_format}, cause then you don't need it.

Related

No route found for "GET /Index" when generating Symfony controller

I am using generate:controller to create a new controller in my Symfony 3 application. But the route is not getting found.
Here is the input/output of the command ...
First, you need to give the controller name you want to generate.
You must use the shortcut notation like AcmeBlogBundle:Post
Controller name: ApplicationSonataPageBundle:Page
Determine the format to use for the routing.
Routing format (php, xml, yml, annotation) [annotation]: yml
Determine the format to use for templating.
Template format (twig, php) [twig]:
Instead of starting with a blank controller, you can add some actions now. An action
is a PHP function or method that executes, for example, when a given route is matched.
Actions should be suffixed by Action.
New action name (press <return> to stop adding actions): IndexAction
Action route [/Index]:
Template name (optional) [ApplicationSonataPageBundle:Page:index.html.twig]:
New action name (press <return> to stop adding actions):
Summary before generation
You are going to generate a "ApplicationSonataPageBundle:Page" controller
using the "yml" format for the routing and the "twig" format
for templating
Do you confirm generation [yes]?
... and here is the content of the new controller class:
namespace Application\Sonata\PageBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class PageController extends Controller
{
public function IndexAction()
{
return $this->render('ApplicationSonataPageBundle:Page:index.html.twig', array(
// ...
));
}
}
... which is not called. I instead receive the following error in the browser:
No route found for "GET /Index"
Is there an additional step I need to do before seeing my action?
What I have tried: I have so far tried every other type of routing (xml, php, yml) without success.
There are a couple of things to check:
Make sure your routes are included inside config/routes.yml
https://symfony.com/doc/3.3/routing.html
https://symfony.com/doc/3.3/routing.html#loading-routes
https://symfony.com/doc/3.3/routing/external_resources.html
Also make sure your bundle is loaded in the kernel: app/AppKernel.php
https://symfony.com/doc/3.3/page_creation.html#bundles-configuration
Another thing I notice, your action/route is capitalized. I'm not sure if this effects things but the common practice is camelCasing so you would have indexAction rather than IndexAction
There is also a command to show routes that are available I believe it is something like php bin/console routes:debug if you run php bin/console it should show you available commands
For what it's worth: I ended up just giving up and copying the following:
_index:
path: /Index
defaults: { _controller: ApplicationSonataPageBundle:Page:Index }
... from the generated yml file into my app's main routing.yml file.

Why localhost:8000 doesn't work, while ...:8000/test works fine on symfony?

Im completely new to Symfony so please bear with me. Im trying to configure my controller to atleast get a working webpage. I created a new Symfony project and started my server. After writing some code into MyController
<?php
namespace AppBundle\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;
class MyController
{
/**
* #Route("/test")
*/
public function numberAction()
{
$prankBro= "Its just a prank bro";
return new Response($prankBro);
}
}
After trying to access localhost:8000 I get a fatal 404 error: No route found for "GET /" Being a complete beginner I have no idea what this is. I believe it is some kind of response type, although I'm not sure. On the other hand if I use localhost:8000/test It seems to be working fine, I get my webpage with a message saying that it was just a prank bro :) Is this how it is supposed to be in symfony? It really messes up with my brain, so if it is fine, can someone explain me why plain localhost:8000 URL gives me 404 error? Thank you!
Take note of the comment above numberAction:
/**
* #Route("/test")
*/
That implies to me that there is a route set up for localhost:8000/test which will execute the numberAction method.
You need to create a method that will be your home page, and then create a route for / which will run your new method. Then when you visit localhost:8000, your new method will be executed.
See the Symphony documentation for details on how to set up routes.

Laravel Authorize() confusion

I'm currently migrating a project from CodeIgniter to Laravel5.
I saw in Laracasts that you can use the Request::authorize() method to authorize access before the controller is called, and it returns true or false.
This would (I think) be the ideal solution as I can contain permission checks within the request, rather than pollute the controller with permission checks and redirections / responses.
The only problem is, when I return false from authorize(), it simply loads an empty white page with forbidden written, and I can't find any documentation on laravel.com on how to template it (either there is no documentation, or I'm overlooking it)
I know I can edit the 404 page in errors/404.blade.php, but I can't work out how to customize the 403 page, which I've tried to add a custom 403.blade.php page, which doesn't get displayed. ( https://mattstauffer.co/blog/laravel-5.0-custom-error-pages )
Is placing these permission checks in the Request a good idea? Or am I missing something?
Update
I ran a backtrace from authorize(), and it looks like it throws an UnauthorizedException, which extends RuntimeException. I've tried catching both in the routes.php file, which doesn't work either.
I've also tried to create middleware, and call the middleware from a method, which doesn't work either, since the middleware's not even called at all.
Update 2
Ok, so I found out that I can only call $this->middleware() from the constructor, not individual methods, which is progress, I guess.
What i do is add a forbiddenResponse() method to Request abstract class. You can return a response object from that method to render a human readable error.
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Http\JsonResponse;
abstract class Request extends FormRequest {
public function forbiddenResponse()
{
return new JsonResponse('Unauthorized', 403);
// or return Response::make('Unauthorized', 403);
}
}
Check the app\Exceptions\Handler.php file. That's where you can customize your exception handling.
The 403 error launches a HttpException. By default, Laravel will look under your resources\views\errors\ directory and try to find a view that corresponds to the same status code. Since you already said that you've created a file called 403.blade.php inside that folder, it should render this page for 403 errors.
One last thing, remember to check inside your web server config file (httpd.conf for Apache, sites-available\your-host for Nginx), if you have a default behavior for any error. If you're using Homestead, you can check the Nginx config file for anything like error_page 404 /index.php;, comment the line and restart the service. That's not the ideal scenario but usually works.
Override the method within your form request object
class CreateUserRequest extends FormRequest {
public function forbiddenResponse(){
return abort(403);
}
}

Symfony cannot find the template file

I have follow all the steps related to Symfony installation, and I try the examples of the Symfony book (provided by the Symfony web site). Currently I am on Controllers chapter (5) and I try the following code:
namespace MyBundle\FrontBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
class HelloController extends Controller
{
public function indexAction($name, Request $request)
{
return $this->redirect($this->generateUrl('front_buy'), 301);
}
public function buyAction(Request $request)
{
return $this->render(
'Hello/buy.html.twig',
array(
'name' => 'Nikos'
)
);
}
}
but I get the following error:
INFO - Matched route "front_buy" (parameters: "_controller": "MyBundle\FrontBundle\Controller\HelloController::buyAction", "_route": "front_buy")
CRITICAL - Uncaught PHP Exception InvalidArgumentException: "Unable to find template "Hello/buy.html.twig"." at /var/www/projects/symfony/vendor/symfony/symfony/src/Symfony/Bridge/Twig/TwigEngine.php line 128
Context: {"exception":"Object(InvalidArgumentException)"}
I know is not something fancy, but I don't know how to fix the problem.
My view file is under the following path : ./src/MyBundle/FrontBundle/Resources/views/Hello/buy.html.twig.
You need to render it with the following syntax:
$this->render('AcmeBlogBundle:Blog:index.html.twig')
or with this syntax
$this->render('#BlogBundle/Blog/index.html.twig')
An Example:
$this->render('#FrontBundle/Hello/buy.html.twig)
More information can be found on the documentation, also refering to symfonys best practices templates should be stored in app/Ressources/views
in "app/config/config.yml" be sure to have this:
framework:
# ...
templating:
engines: ['twig']
In my case, the problem was really related to the specific version of Symfony.
My project used to be run with Symfony 2.8.19. I tried to migrate it to another Linux
evironment (uning symfony2.8.42) and then I got the very same error with the same code (very wierd).
I tried the solutions mentioned before and none worked like using :
$this->render('#BlogBundle/Blog/index.html.twig')
or
$this->render('AcmeBlogBundle:Blog:index.html.twig').
After several tries, I found the problem. In fact, in my old env, I had :
return $this->render('XxxxxBundle:Default:zzzz.html.twig';
But the problem was with Capitalized Default because the real path was with an uncapitalized default
so changing it to the following fixed the problem in my new env:
return $this->render('XxxxxBundle:default:zzzz.html.twig';

Routes not working in FOSRestBundle and Symfony

I've been going round in circles with this one. I've been either getting 500 errors saying template cannot be rendered or found, or when I attempt to use the annotations, they clash with the fact I'm using Symfony's annotations for my routes. With the current code, I'm just getting 404's.
My config:
# config.yml
fos_rest:
routing_loader:
default_format: json
An example of my controller:
namespace IGIG\GigBundle\Controller;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Controller\Annotations\Route;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use IGIG\GigBundle\Document\Gig;
class GigApiController extends FOSRestController
{
public function getGigsAction()
{
$gigs = $this->get('doctrine_mongodb')
->getRepository('IGIGGigBundle:Gig')
->findAll();
$view = $this->view($gigs, 200)
->setTemplate("IGIG:GigBundle:getGigs.html.twig")
->setTemplateVar('gigs');
return $this->handleView($view);
}
}
Routing
gigs:
prefix: /api
type: rest
resource: IGIG\GigBundle\Controller\GigApiController
I should also add, the .html.twig file within the controller doesn't actually exist, I was under the impression that it was automatically generated, is that the case?
Thanks in advance!
First of all it looks like your config is not indented properly, but might also just be a copy/paste error, otherwise it should throw an exception for you.
# config.yml
fos_rest:
routing_loader:
default_format: json
I should also add, the .html.twig file within the controller doesn't actually exist, I was under the impression that it was automatically generated, is that the case?
No, you do need to generate that template file yourself and that is probably the cause for your 500 errors. However if you don't intend to use twig templates next to your REST API, so if you ever only want to return JSON responses, then you won't need them at all and can remove the calls from your controller too.
For your 404's: do a ./app/console router:debug | grep api and see if the generated routes are like what you expect.
You should have a look at the bundle documentation again, in particular the full config reference: https://github.com/FriendsOfSymfony/FOSRestBundle/blob/master/Resources/doc/configuration-reference.md
And I found this very helpful too when starting out with REST APIs with Symfony: http://welcometothebundle.com/symfony2-rest-api-the-best-2013-way/

Categories