In Symfony 1 we can access an action in template page as for example url_for('modulename/actionname') without writing anything in routing.yml.
how is this possible in Symfony2?,that is if i have to access more than one action in a twig without specifying in routing.this is useful while using ajax.
Thanks in advance
If I understand your question correctly, you're asking how you can generate a url by passing a module name and action name, instead of a route name. Is that right?
I don't think this is possible in Symfony2. If you take a look at the generate method in Symfony\Component\Routing\Generator\UrlGenerator you'll see that it expects a route's name as the first parameter. Also, Symfony2 doesn't natively support the generic routes that symfony 1 does (shown below for reference).
default_index:
url: /:module
param: { action: index }
default:
url: /:module/:action/*
Without these generic routes, you can't simply access /myModule/myAction without actually defining a route for it. And don't forget that Symfony2 now uses bundles, which would complicate this further.
So for whatever actions you want to access, you'll need to write routes for them.
In order to actually generate the URLs...
- From a controller: $this->generateUrl($routeName);
- From a PHP template: $view['router']->generate($routeName);
- From a Twig template: {{ path('_routeName') }} or {{ url('_routeName') }} for an absolute URL
Additionally to Arms' words, here are few examples (with parameters):
Let's say our routing is:
#routing.yml
acme_demo_page:
path: /{page}.{_format}
defaults:
_controller: AcmeDemoBundle:Page:index
We'll generate the URL for this routing, as follows:
From any controller's action:
$url = $view['router']->generate("acme_demo_page", array(
"page" => "main",
"_format" => "html",
));
From any PHP template:
$url = $this->generateUrl("acme_demo_page", array(
"page" => "main",
"_format" => "html",
));
From any Twig template:
Home
Abs Home
Hope it helps.
Cheers.
Related
I have a url.py inside my project which includes the following urls.py (belongs to my app).
urls.py
from django.urls import path,include
from .views import Index, Foo
bar_urlpatterns = [
path('foo/', Foo.as_view(), name='foo'),
]
urlpatterns = [
path('', Index.as_view(), name='index'),
path('bar/', include(bar_urlpatterns)),]
I'm trying to outsource the subpaths of a path. The docs says the function include can include
a pattern_list and when i call the url"http://myurl/foo/bar" directly, this seems to hold true. I can also load the view via ajax directly when i give it the string.
But when i try to use the reverse {%url 'foo'} url template tag this throws:
Uncaught SyntaxError: Invalid regular expression flags(at ...)
Doing the same thing with non-outsourced url patterns works perfectly fine for me.
The html elements where i use the function:
<a onclick="load_tab_view({% url "foo" %})">Foo</a>
<div id="tab_view_replaceable"></div>
js (works fine with my other views)
function load_tab_view(url){
replace_id = 'tab_view_replaceable';
$.ajax({
url: url,
type: 'GET',
dataType: 'html',
success: function(data){
$('#'+replace_id).html(data);
}
});
}
Is there a way in which im still able to outsource my subpaths and make use of the reverse url template tag?
(I dont want to create a new app for bar)
You should be able to use it if you put it in a different kind of quotation marks. So alternate between the 3 types.
In your case it should work like:
<a onclick="load_tab_view(`{% url 'foo' %}`)">Foo</a>
<div id="tab_view_replaceable"></div>
That's because JS doesn't take it as string otherwise.
I would like to setup axios to delete a record using a resource route:
axios.delete('/job-management', this.deletedata).then((res)=>{
console.log(res);
})
For my routes I have:
Route::resource('job-management', "PositionsController", [ 'as' => 'jobs']);
Now, in my PositionsController I have:
public function destroy(Positions $positions) {
return $positions;
}
But the above always returns "method not allowed". How can I handle a delete request with the axios delete() method?
Laravel throws the MethodNotAllowedHttpException when we attempt to send a request to a route using an HTTP verb that the route doesn't support. In the case of this question, we see this error because the JavaScript code sends a DELETE request to a URL with the path of /job‑management, which is handled by a route that only supports GET and POST requests. We need to change the URL to the conventional format Laravel expects for resourceful controllers.
The error is confusing because it hides the fact that we're sending the request to the wrong URL. To understand why, let's take a look at the routes created by Route::resource() (from the documentation):
Verb URI Action Route Name
GET /job-management index job-management.index
GET /job-management/create create job-management.create
POST /job-management store job-management.store
GET /job-management/{position} show job-management.show
GET /job-management/{position}/edit edit job-management.edit
PUT/PATCH /job-management/{position} update job-management.update
DELETE /job-management/{position} destroy job-management.destroy
As shown above, URLs with a path component of /job-management are passed to the controller's index() and store() methods which don't handle DELETE requests. This is why we see the exception.
To perform a DELETE request as shown in the question, we need to send the request to a URL with a path like /job-management/{position}, where {position} is the ID of the position model we want to delete. The JavaScript code might look something like:
axios.delete('/job-management/5', this.deletedata).then((res) => { ... })
I've hardcoded the position ID into the URL to clearly illustrate the concept. However, we likely want to use a variable for the this ID:
let positionId = // get the position ID somehow
axios.delete(`/job-management/${positionId}`, this.deletedata).then((res) => { ... })
The URL in this form enables Laravel to route the DELETE request to the controller's destroy() method. The example above uses ES6 template string literals because the code in the question suggests that we're using a version of JavaScript that supports this feature. Note the placement of backticks (`) around the template string instead of standard quotation marks.
as I can see in your code above, you pass Positionseloquent as a parameter to destroy method but in your vueJS you don't pass this object. for that you would pass it like this :
axios.delete('/job-management/${id}').then((res)=>{
console.log(res);
})
and the id param inside the url of ur axios delete, it can object of data or any think.
i hope this help you
I have a small problem with a Javascript variable in a Twig template,
what I want is to pass a variable as a parameter (in a url) to a function. All I have found on StackOverflow is how to pass a string 'blablabla' to the URL like:
url/{param}, {'param' : 'blablabla'}
but I want something like :
$var =...;
url/{param}, {'param': $var}
this photo should make it clear to you , thanks for reading
photo
I advise you to use the FOS JsRouting bundle. It is totally suited to what you want to do.
Here is the official documentation : https://symfony.com/doc/current/bundles/FOSJsRoutingBundle/usage.html
Example in Twig :
Routing.generate('your_route_with_params', { param: varJavascript });
Enjoy
I'm trying to create a game with symfony in which there are warriors. Each warrior has a level. To understand jquery and ajax which i'm new with, i want to create a simple button which when clicked use jquery ajax to get the warrior id and make him lvl up. Here is the level up method controller :
public function warriorLevelUpAction(Warrior $warrior){
$warrior->levelUp();
return $this->render('StormbladesWarriorBundle:Warrior:homepage.html.twig', array(
'warrior' => $warrior
));
}
Here is my Jquery ajax method
$('#cpt').click(function() {
$.ajax({
url: "/stormblades/web/app_dev.php/warriors/levelUp/"+{{ warrior.id }},
error: function(xhr, error){
console.debug(xhr);
console.debug(error);
}
});
And here is my routing :
stormblades_warrior_leveluppage:
path: /warriors/levelUp/{id}
defaults: { _controller: StormbladesWarriorBundle:Warrior:warriorLevelUp }
requirements:
id: \d+
Obviously, this doesn't work, i got a beautiful error 500. Any help and suggestion on what's wrong would be appreciate.
A couple of things stand out to me.
Firstly, your warriorLevelUpAction function requires a warrior object, but in the request you are only passing an id. Therefore, you require an extra step to get the warrior by it's ID then level up. For example:
public function warriorLevelUpAction($id){
$warrior = $this->getDoctrine()
->getRepository('StormbladesWarriorBundle:Warrior')
->find($id);
$warrior->levelUp();
return $this->render('StormbladesWarriorBundle:Warrior:homepage.html.twig', array(
'warrior' => $warrior
));
}
Secondly, if you are only ever going to call this function through AJAX, then you could just return a HTTP 200 Status OK, rather then render homepage.html.twig. You don't have to but, I just find it more efficient. Something like this should be fine:
$response = new Response(Response::HTTP_OK);
return $response;
Lastly, in your AJAX code, the url should be: "/warriors/levelUp/"+{{ warrior.id }}, unless there is a specific reson you are using the full path. This path will work in both development and production, whereas your current code will always run in Debug Mode.
everything said above +....
allow POST in your route through the method : POST attribute like this ( probably the reason of the 500)
defaults : ......
requirements:
_method: POST
As jrmck said , in your controller, either return a Reponse object or
return $this->container->get('templating')->renderResponse('..:page.html.twig',
array( 'var' => $var ));
If you can, use FOSJSRoutingBundle (symfony routes for javascript). Calling routes by URL is not that great if you change of adress or anything. https://github.com/FriendsOfSymfony/FOSJsRoutingBundle.
Or also
url: "{{ path('my_route_php")}}",
So I want to call REST service with the following URL patterns:
1.domain.com/service.svc/action1/sessionid/objectid
2.domain.com/service.svc/action2/sessionid/objectid/objectid2
3.domain.com/service.svc/action3/sessionid/objectid
4.domain.com/service.svc/action4/sessionid/objectid/objectid3/objectid4
5.domain.com/service.svc/action5/sessionid/objectid4/objectid5/objectid6/objectid2
and I ended up with this resource object:
var object = $resource('domain.com/service.svc/:actionName/:sessionId/:objectid:objectid4/
:objectid2:objectid3:objectid5/:objectid4:objectid6/:objectid2:', {}, {});
And I can call:
object.get({
'action1': action1,
'sessionid': sessinId,
'objectid': objectid
})
I see the problem here with the URL template, it looks cumbersome to read.The second problem is that URL number 2 expects objectid2 in one location in URL, and then URL number 5 expects the same parameter at the end of url.This breaks URL template, so I had to rename one of the them.Is there a better solution for this particular problem, and what are the best practices regarding REST services with these complex URI's ?