In Yii, is there a way to have urlFormat => path but still pass query params with an ampersand? - yii

Currently (in Yii 1.1.13) all createUrl methods put extra params in the 'path style', which means I cannot then override them by submitting a form, because they take precedence over those that come in a query string. Is there a way to always pass extra parameters in query string but still have the url look normal and not butt-ugly like with the get urlFormat?

You can set appendParams to false in your urlManager component configuration.

Related

Dot.NET Core Routing and Controller Processing discrepancy

I am trying to use the asp-route- to build a query string that I am using to query the database.
I am confused on how the asp-route- works because I do not know how to specifically use the route that I created in my cshtml page. For example:
If I use the old school href parameter approach, I can then, inside my controller, use the specified Query to get the parameter and query my database, like this:
If I use this href:
#ulsin.custName
then, in the controller, I can use this:
HttpContext.Request.Query["ID"]
The above approach works and I am able to work with the parameter. However, if I use the htmlHelper approach, such as:
<a asp-controller="Report" asp-action="Client" asp-route-id="#ulsin.ID">#ulsin.custName</a>
How do I get that ID from the Controller? The href approach does not seem to work in this case.
According to the Anchor Tag Helper documentation, if the requested route parameter (id in your case) is not found in the route, it is added as a query parameter. Therefore, the following final link will be generated: /Report/Client?id=something. Notice that the query parameter is lowercase.
When you now try to access it in the controller as HttpContext.Request.Query["ID"], since HttpContext.Request.Query is a collection, indexing it would be case-sensitive, and so "ID" will not get you the query parameter "id". Instead of trying to resolve this manually, you can use a feature of the framework known as model binding, which will allow you to automatically and case-insensitively get the value of a query parameter.
Here is an example controller action that uses model binding to get the value of the query parameter id:
// When you add the id parameter, the framework's model binding feature will automatically populate it with the value of the query parameter 'id'.
// You can then use this parameter inside the method.
public IActionResult Client(int id)

Dojo dStore Rest dGrid sort parameter

When I fetch from a dStore the URL looks something like this
http://localhost/rest/dojo?department=sales
which works fine. If I then click in the header of the dGrid the sent URL looks like this.
http://localhost/rest/dojo?department=sales&sort(+id)&limit(25)
Shouldn't it send &sort=+id&limit=25? I am using Java and Spring for the backend and it expects the parameters to be formatted this way. Right now I can not receive the extra parameters. Is there a way to get it to send the parameters the way Spring is expecting them?
sort(...) and limit(...) are the default behaviors of dstore/Request (which Rest extends), but these can be customized via sortParam for sort, and useRangeHeaders or rangeStartParam and rangeCountParam for range.
For example, to result in &sort=+id&limit=25 as you requested, you could set up your store as follows:
var store = new Rest({
target: '...',
sortParam: 'sort',
rangeStartParam: 'offset',
rangeCountParam: 'limit'
});
I've additionally assumed above that offset is the GET parameter you'd want to use to indicate what record to start at when requesting ranges. Generally if you're not using range headers (useRangeHeaders defaults to false) and you want to set a count GET parameter, you'll also need to set a start GET parameter.
These properties are listed in the Request Store documentation.

Multiple GET parameters in UrlManager

I am using Yii 1.1.14.
I want to convert
http://website.com/controller/action?param1=value1&param2=value2
to
http://website.com/value1/value2
How to do this in urlManager?
First, check this to hide index.php:
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#hiding-x-23x
Then, the route in config.php should be like this:
'<param1:\w+>/<param2:\w+>'=>'mycontroller/myaction',
The method myaction should accept $param1 and $param2 in its constructor to be passed automatically by Yii.
This would make your app unable to look for other controllers, because that rule will accept every route with 2 words separated by /

How can I access query string parameters for requests I've manually dispatched in Laravel 4?

I'm writing a simple API, and building a simple web application on top of this API.
Because I want to "consume my own API" directly, I first Googled and found this answer on StackOverflow which answers my initial question perfectly: Consuming my own Laravel API
Now, this works great, I'm able to access my API by doing something like:
$request = Request::create('/api/cars/'.$id, 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
This is great! But, my API also allows you to add an optional fields parameter to the GET query string to specify specific attributes that should be returned, such as this:
http://cars.com/api/cars/1?fields=id,color
Now the way I actually handle this in the API is something along the lines of this:
public function show(Car $car)
{
if(Input::has('fields'))
{
//Here I do some logic and basically return only fields requested
....
...
}
I would assume that I could do something similar as I did with the query string parameter-less approach before, something like this:
$request = Request::create('/api/cars/' . $id . '?fields=id,color', 'GET');
$instance = json_decode(Route::dispatch($request)->getContent());
BUT, it doesn't seem so. Long story short, after stepping through the code it seems that the Request object is correctly created (and it correctly pulls out the fields parameter and assigns id,color to it), and the Route seems to be dispatched OK, but within my API controller itself I do not know how to access the field parameter. Using Input::get('fields') (which is what I use for "normal" requests) returns nothing, and I'm fairly certain that's because the static Input is referencing or scoping to the initial request the came in, NOT the new request I dispatched "manually" from within the app itself.
So, my question is really how should I be doing this? Am I doing something wrong? Ideally I'd like to avoid doing anything ugly or special in my API controller, I'd like to be able to use Input::get for the internally dispatched requests and not have to make a second check , etc.
You are correct in that using Input is actually referencing the current request and not your newly created request. Your input will be available on the request instance itself that you instantiate with Request::create().
If you were using (as you should be) Illuminate\Http\Request to instantiate your request then you can use $request->input('key') or $request->query('key') to get parameters from the query string.
Now, the problem here is that you might not have your Illuminate\Http\Request instance available to you in the route. A solution here (so that you can continue using the Input facade) is to physically replace the input on the current request, then switch it back.
// Store the original input of the request and then replace the input with your request instances input.
$originalInput = Request::input();
Request::replace($request->input());
// Dispatch your request instance with the router.
$response = Route::dispatch($request);
// Replace the input again with the original request input.
Request::replace($originalInput);
This should work (in theory) and you should still be able to use your original request input before and after your internal API request is made.
I was also just facing this issue and thanks to Jason's great answers I was able to make it work.
Just wanted to add that I found out that the Route also needs to be replaced. Otherwise Route::currentRouteName() will return the dispatched route later in the script.
More details to this can be found on my blog post.
I also did some tests for the stacking issue and called internal API methods repeatedly from within each other with this approach. It worked out just fine! All requests and routes have been set correctly.
If you want to invoke an internal API and pass parameters via an array (instead of query string), you can do like this:
$request = Request::create("/api/cars", "GET", array(
"id" => $id,
"fields" => array("id","color")
));
$originalInput = Request::input();//backup original input
Request::replace($request->input());
$car = json_decode(Route::dispatch($request)->getContent());//invoke API
Request::replace($originalInput);//restore orginal input
Ref: Laravel : calling your own API

Completely custom path with YII?

I have various products with their own set paths. Eg:
electronics/mp3-players/sony-hg122
fitness/devices/gymboss
If want to be able to access URLs in this format. For example:
http://www.mysite.com/fitness/devices/gymboss
http://www.mysite.com/electronics/mp3-players/sony-hg122
My strategy was to override the "init" function of the SiteController in order to catch the paths and then direct it to my own implementation of a render function. However, this doesn't allow me to catch the path.
Am I going about it the wrong way? What would be the correct strategy to do this?
** EDIT **
I figure I have to make use of the URL manager. But how do I dynamically add path formats if they are all custom in a database?
Eskimo's setup is a good solid approach for most Yii systems. However, for yours, I would suggest creating a custom UrlRule to query your database:
http://www.yiiframework.com/doc/guide/1.1/en/topics.url#using-custom-url-rule-classes
Note: the URL rules are parsed on every single Yii request, so be careful in there. If you aren't efficient, you can rapidly slow down your site. By default rules are cached (if you have a cache setup), but I don't know if that applies to dynamic DB rules (I would think not).
In your URL manager (protected/config/main.php), Set urlFormat to path (and toptionally set showScriptName to false (this hides the index.php part of the URL))
'urlManager' => array(
'urlFormat' => 'path',
'showScriptName'=>false,
Next, in your rules, you could setup something like:
catalogue/<category_url:.+>/<product_url:.+> => product/view,
So what this does is route and request with a structure like catalogue/electronics/ipods to the ProductController actionView. You can then access the category_url and product_url portions of the URL like so:
$_GET['category_url'];
$_GET['product_url'];
How this rule works is, any URL which starts with the word catalogue (directly after your domain name) which is followed by another word (category_url), and another word (product_url), will be directed to that controller/action.
You will notice that in my example I am preceding the category and product with the word catalogue. Obviously you could replace this with whatever you prefer or leave it out all together. The reason I have put it in is, consider the following URL:
http://mywebsite.com/site/about
If you left out the 'catalogue' portion of the URL and defined your rule only as:
<category_url:.+>/<product_url:.+> => product/view,
the URL Manager would see the site portion of the URL as the category_url value, and the about portion as the product_url. To prevent this you can either have the catalogue protion of the URL, or define rules for the non catalogue pages (ie; define a rule for site/about)
Rules are interpreted top to bottom, and only the first rule is matched. Obviously you can add as many rules as you need for as many different URL structures as you need.
I hope this gets you on the right path, feel free to comment with any questions or clarifications you need