Laravel reverse routing - route url needs query string attached - hyperlink

In a view, I want to create a link (generate the url) to a route. I believe this is called “reverse routing.” I want to add a query string to the generated url.
The target routes need to take a query string parameter to specify what kind of view to return, e.g. partial, basic, full. I will also be adding other query string params for search terms and fields. I will need to pass these on to my api that is called with my dispatcher (consuming my own api).
Route::get('thing/{id}', [
'uses' => 'path\to\namespace\ThingController#show',
'as' => 'thng.show']);
Route::get('thing/form/{id?}', [
'uses' => 'path\to\namespace\ThingController#form',
'as' => 'thng.form']);
In a view:
<td>{{ link_to_route('thng.show?filter="partial"', $row->title,
['id' => $row->id]) }}</td>
I tried simply appending ?string to the route name within link_to_route, but that doesn't work (Error = Route [lstg.show?filter="partial"] not defined). I'm not sure how to hard-code it either since it's a named route and does take a named route parameter.

In your case I guess you should try something like this:
<td>{{ link_to_route('thng.show', $row->title, ['filter' => 'partial', 'id' => $row->id]) }}</td>
Note: Using link_to_route function you should distinguish URL parameters (query string) which is third argument and HTML attributes of anchor tag itself, which is last argument.

Related

How does this rails route match any incoming action to it's correlated method on the controller?

I have a Rails route defined like this:
match '/test_report(/:action)' => 'test_report#index', via: :all
I am not an expert on Rails routing, but using context clues I would have expected that this route to map any request like /test_report/some_action or /test_report/other_action to the index method on the TestReportController, because of the part of the route definition after the hash rocket: => 'test_report#index'.
However, this is not the behavior. Instead, I can create another method on the TestReportController called update_report, and then I can POST to /test_report/update_report to trigger the update_report method. From the route definition I'm using, I wouldn't expect this to work, but it does. I would have expected the POST to hit the index method on the controller.
Note: Just so we're clear, I do understand that the (/:action) part of the route marks it as an optional part of the URL, and the :action symbol is special here and is interpreted as an action's name.
TL;DR:
If the => 'test_report#index' in the above route doesn't map all requests to the index method on the controller, what does it actually do?
As you probably know, whatever parameters you define within the route pattern become available in the params hash in the controller.
So in your example, :action becomes available within the controller as params[:action], which is also used internally by Rails to load the correct action. (If you inspect, you'll see params[:route], params[:controller], params[:action], etc.)
I'm guessing that defining your own :action in the URL pattern like that causes Rails to prefer that over what's in your mapping (skipping the index in test_report#index).
If you want to live in both worlds, you'll probably want to name it something other than :action.

how to pass '?' character in url (rails)

i want to pass a query to url like
http:/localhost:3000/saldo/;1010917745800000015?1
in my routes i have:
get 'saldo/:nomor' => 'kartus#show_saldo' , as: :show_saldo
and controller:
def show_saldo
#kartu = Kartu.find_by_nomor(params[:nomor])
end
but instead i get this params
Parameters {"1"=> nil,"nomor"=>";1010917745800000015"}
how can i get my param as {"nomor"=>";1010917745800000015?1"}
<%= link_to 'xyz' show_saldo_path(:nomor => 'nomor', :def => 'def'......) %>
In get everything you passed other than url parameter will become your query parameter. def will become your url parameter. More information here.
? is a special character in urls. If you want to include it in the value of a parameter then you should Uri Encode, eg with CGI.escape(), the parameter before submitting it: this will convert "?" to "%3F", and will similarly convert any other special characters (spaces, brackets etc). So, the parameter that is actually submitted will become "%3B1010917745800000015%3F1".
At the server side, rails will call CGI.unescape on the params, so it should show up in your controller as ";1010917745800000015?1" again.
This should happen automatically with form inputs - ie, if someone writes ;1010917745800000015?1 into a text field then it should actually be sent through as "%3B1010917745800000015%3F1"
If you want people to diagnose why this isn't happening then you should include the html (of the form or link which is submitting this value) to your question.

cakephp url modification: remove action and add slug inflector

I'm trying to remove the action in the cakephp url and add a slug inflector, to be more clear this is my expected output:
from this: example.com/posts/view/81/This is a test post
to this: example.com/posts/This-is-a-test-post
This is my current code:
That gives me this output: example.com/posts/view/This is a test post
Controller:
public function view($title = null) {
if (!$title) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findByTitle($title);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
$this->set('post', $post);
}
view.ctp:
$this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['title']));
I also tried this one,this link being my reference CakePHP: Use post title as the slug for view method :
Output: example.com/posts/view/21/This-is-a-test-post
Controller:
function view($id) {
$this->Post->id = $id;
$this->set('post', $this->Post->read());
}
view.ctp
$this->Html->link($post['Post']['title'], array('action' => 'view', $post['Post']['id'], Inflector::slug($post['Post']['title'],'-')));
below are the other links that I tried but failed, I also tried the modifying the routes.php but can't make the proper code to make it work
want to remove action name from url CakePHP
How to remove action name from url in cakephp?
Remove action name from Url in cakephp?
any help/suggestions is appreciated thanks.
Use Id and Named parameter...
On routes.php
define new routes as-
Router::connect('/posts/:id-:title',
array('controller' => 'posts',
'action' => 'view')
);
This new defined routes will match and parse all url containing id and title named parameter..
Important Note:: Do not define new routes after the end of routes.php. Try to define on the middle of the file..
On view
echo $this->Html->link('Hi',array(
'controller' => 'posts',
'action' => 'view',
'id' => 4,
'title' => Inflector::slug('the quick brown fox')
));
Well the solution provided above will fulfill your needs, but still after reading your question one thing comes into my mind... in your controller you are trying to read posts using title I mean this will slow down your system not recommended in programming so use id and increase one more column in your db table for slug(SEO title) which will be used for creating your post urls.
For example:
Post title: This is a test post
Create seo title for this as: this-is-a-test-post-123
Stor seo title in DB as <this-is-a-test-post>
See 123 is your posts ID now change your controller function to get data based on id ie.123, I hope you cn extract 123 from the sting easily...
Note: remember you have to think about this-is-a-123 string also because
they also land in post having id 123.
Use below route for the above solution:
Router::connect('/posts/*', array('controller' => 'posts', 'action' => 'view'),array('pass' => array('title')));
Now in your controller:
You will get string "this-is-a-test-post-123" in $post_title
function view($post_title=null){
$temp = explode('-',$post_title);
$posts_id= end($temp);
$lastKey = end(array_keys($temp));
unset($temp[$lastKey]);
$seoTitle = implode("-",$temp);
//Now compare the above seoTitle with DB seo title for unique urls
}

How to hide everything(id) in the URL in the browser except the site name and controller name in yii?

How to hide/encrypt everything(id) in the URL in the browser except the site name and controller name?
I think UrlManager can do it, but I don't know how ? need url mapping similar in ROR
my url manager code
'urlManager'=>array(
//'urlFormat'=>'path',
'showScriptName'=> false,
'rules'=>array(
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
I like to add a random number between every action(for secure my urls)
ROR eg:
map.connect 'by/:develop_name',
:controller => 'developer',
:action => 'builder_projects'
Please explain step by step.
couple if links I found relate to this
LINK1
LINk2
You just need to specify your application routes appropriately. Before continuing, you should read the URL management chapter of the Yii guide.
What you want to do is use named parameters in your rules, which means that the rule definition would look like this:
'by/<id:\w+>' => 'developer/builder_projects'
This rule takes a URL of the form http://site.com/index.php/by/42 and routes it to the controller developer, action builder_projects with the parameter id equal to whatever 42 (this is what the regular expression \w+ matches).
Routes are specified in your application configuration file as parameters to the urlManager component:
'urlManager' => array(
'urlFormat' => 'path',
'rules' => array(
'by/<id:\w+>' => 'developer/builder_projects'
// more rules
),
),
What you could do is define a helper function which symmetrically encrypts/decrypts:
class Helper {
public static function myCrypt($data, $decrypt = false){
//Logic to encrypt/decrypt
return $result;
}
}
and then when you create urls you can do:
$this->createUrl("myRoute", array("secret_id" => Helper::myCrypt($secret_id)));
and then in the controller action this resolves to you can do this:
public function actionMyRoute($secret_id){
$secret_id = Helper::myCrypt($secret_id, true);
//Do what you need to do with the decrypted id
}
Just make sure your encryption method returns a url safe string.

Use a string with forward slashes as a single parameter in routes.rb

Sorry about that confusing title :) I have a resource, ComatosePage (used in the comatose cms plugin), which has a table called comatose_pages which has a field 'full_path' which has values like this: "en/home/logged-in/subscriber/school-top" to set up a route so that i can use this full_path field to load a ComatosePage from the db, instead of the standard id field, so that this url:
/comatose_admin/en/home/logged-in/subscriber/school-top
loads the comatose_admin controller's edit action, passing everything after comatose_admin/ through as a parameter, ie generates this for rails:
Parameters: {:controller => "comatose_admin", :action => "edit", :full_path => "en/home/logged-in/subscriber/school-top"}
The complication lies in the fact that the string is broken up with forward slashes, which is going to confuse routes, i think. Can i set up routes to take everything after "comatose_admin/" and put it into a single parameter?
You can use wildcards in your routes that will match forward slashes. Try something like this:
"/comatose_admin/*full_path"
Then params[:full_path] should contain the rest of the request path.
See Route Globbing

Resources