I've not clear how handling the exception MethodNotAllowedException in Symfony. Let me explain,
ON VIEW
Suppose that we written this script on View to go to the Controller:
//Script on view to go to the controller
<script type="text/javascript">
$.ajax({
method: "POST",
url: "{{ path('my_path') }}",
data: { myValue }
}).done(function( data ) {
//do something
});
</script>
Define the route
We define the sending of data using the post method. Now, see it the route in routing.yml
//scr/myBundle/Resources/routing.yml
my_path:
path: /my-path
defaults: { _controller: myBundle:myMain:doAndReturnSomething }
methods: [POST]
Working on Controller
Now, in controller
//scr/myBundle/Resources/Controller/myMainController
class myMainController extends Controller{
public function doAndReturnSomethingAction()
{
//doSomeThing
return $this->render('myBundle:myViews:view.html.twig');
}
This works great. How we can see, the method defined to do the send is POST.
Now, when we reload the page with the browser or press f5. All works fine. But, if we press enter in the url on browser
//Click on: localhost/myAplicationDir/web/my-path
The aplication get broken, sure by we don't define sending with GET, I suppose.
How can I get this exception in Symfony and show the user a custom page?
I'm thinking in redirect to myBundle index page. Any sugest?
Thanks for help. I'm just starting with PHP and Symfony.
SOLUTION
Solution #1
Create two separate routers with GET and POST methods respectively
Solution #2
I wouldn't like created two separate routes. My controller has many methods. I wouldn't like send the data via GET by URL. But I wouldn't like that my application get broken.
//scr/myBundle/Resources/routing.yml
my_path:
path: /my-path
defaults: { _controller: myBundle:myMain:doAndReturnSomething }
methods: [POST, GET]
//scr/myBundle/Resources/Controller/myMainController
use Symfony\Component\HttpFoundation\Request;
class myMainController extends Controller{
public function doAndReturnSomethingAction(Request $request)
{
if ($request->getMethod() == 'POST')
//doSomeThing
else
//redirect to index
//This can be other way
//myValue is sending via POST
if ($request->get('myValue') != null)
//doSomething
else
//redirect to index
//return $this->render('myBundle:myViews:view.html.twig');
}
It's there any method for correct this in all routes on routing.yml??
POSTand aGETroute why don't just add it to themethodskey in therouting.yml?