Codeigniter URI routing with for multiple methods - codeigniter-2

I am working on codeigniter. Controller name is "project" and 4 functions are there.."get_city_data", "get_store_data", "get_currency", "get_description".
Parameters I am passing in above 2 functions are - get_city_data($state, $city), get_place_data($state, $city, $store).
So on browser to render these functions I am using the urls respectively as-
http://localhost/project/get_city_data/state1/city1
I want to change the urls like
http://localhost/state1/city1
In routes.php if I define a route like this
$route['(:any)/(:any)'] = 'project/get_city_data/$1/$2' then it reflects for all other functions as well but I want to change urls for these 2 functions only.
Also I do not want to use _remap function as it doesn't go well with my needs.
Can anybody help me in this?
ThankYou

I suggest you to check in the database at first, then determine the routes required. Here is my answer for your requirement.
In your routes.php, try this code:
require_once( BASEPATH . 'database/DB' . EXT );
$url_source = $_SERVER['REDIRECT_URL'];
$arr_url = explode("/", $url_source);
$state_name = $arr_url[3];
$city_name = $arr_url[4];
$store_name = $arr_url[4];
$db = & DB();
//Let say grab 3 columns to be check
$db->select('state_name, city_name, store_name');
if(!empty($state_name)):
$db->where('state_name', $state_name);
endif;
if(!empty($city_name)):
$db->where('city_name', $city_name);
endif;
if(!empty($store_name)):
$db->where('store_name', $store_name);
endif;
$query = $db->get('table', 1);
$obj = $query->row();
if ($obj):
$route["$obj->state_name/$obj->city_name/$obj->store_name"] = "project/get_city_data/$state_name/$city_name/$store_name";
endif;
You can try by this url to test:
http://localhost/state_name/city_name/store_name

I got it solved using regex.
In routes.php i wrote
$url_source = $_SERVER['REQUEST_URI'];
if(!(preg_match('%^/project/get_description\?state=[a-zA-Z_-]*%', $url_source) || preg_match('%^/project/get_currency\?state=[a-zA-Z_-]*%', $url_source))){
if(!preg_match('%^\/[a-zA-Z_-]+\/[a-zA-Z_-]+\/[a-zA-Z_-]+$%', $url_source)){
$route['(:any)/(:any)'] = 'project/get_city_data/$1/$2';
}else{
$route['(:any)/(:any)/(:any)'] = 'project/get_store_data/$1/$2/$3';
}
}
This way I was able to route for particular functions.

Related

How to Route Codeigniter with URI Segments there

how to route properly url with segments in codeigniter.
this is my url .
https://www.test.com/region/india/about/people/gaurav-Singh/1
this is in my route
$route['region/india/about/people/(:any)/(:any)'] = "region/india/memberview/$1/$2";
this is my controller
public function memberview()
{
$teamid = $this->uri->segment(5);
$data['view'] = 'region/india/team-member-view.php';
$this->load->model('region/India_model');
$data['team'] = $this->India_model->tmview($teamid);
$this->load->view('region/layout', $data);
}
this is my model
public function tmview($teamid){
$this->db->query("select * from ojiteam");
$this->db->where('id',$teamid);
$query = $this->db->get();
return $query->result_array();
}
in my view i am showing data with
<?php echo $team['tmname'];?>
but its not working, it is showing 500 error.
help me with this issue. i have searched and went through codeigniter but not able to solve this.
Depending on the environment you are working on (see docs) you can debug to figure out what is causing this 500 error. Usually this means somehting is wrong with your code, you will have to debug to find out what file and line this error is generated from.
To use numbers in your routing you should do (:num), this way only numbers are allowed on that part of your routing (see docs).
On the controller part, you can pass variables to your controller from your routing options, so;
$route['region/india/about/people/(:any)/(:any)'] = "region/india/memberview/$1/$2";
public function memberview( $area, $teamid )
{
// Your coding
// $area now is; gaurav-Singh
// $teamid now is; 1
}
This way you don't have to worry about which part of the URL you need to use because it's all set.

Load view by current URL last segment in Codeigniter

I'm trying to load view content page when url last segment matched. When click a link which get link in url like http://192.168.20.2/vtp/attendance/rawAttendance then load the rawAttendance view and when I click other link which last segment is getAttendance then it's also load the same same view not getAttendance. How do get this done?
$last = $this->uri->total_segments();
$lastSegment = $this->uri->segment($last);
if ($this->input->post("fromAjax")) {
if($lastSegment == "rawAttendance"){
$this->load->view('attendance/rawAttendance', $data);
}else if($lastSegment == "getAttendance"){
$this->load->view('attendance/getAttendance', $data);
}else {
}
}
CI has its inbuilt helper for knowing controller name and method name.
$classname = $this->router->fetch_class();
$methodname = $this->router->fetch_method();
if ($this->input->post("fromAjax")) {
if($classname == "attendance" && $methodname == "rawAttendance"){
$this->load->view('attendance/rawAttendance', $data);
}else if($classname == "attendance" && $methodname == "getAttendance"){
$this->load->view('attendance/getAttendance', $data);
} else {
}
}
CodeIgniter is a basic MVC framework - so everything starts with the controller. From the code you've written, I assume you already have your routes, etc configured to point at the method you've placed in your question.
You can simplify things quite a bit from the way you have them. Using the CI helper for controller/method is a bit helpful, but I think you're looking for something a little more elastic in your approach to dynamically load a view based on your last URI segment.
Try something like this:
// Get your last URI segment
$last = $this->uri->total_segments();
$lastSegment = $this->uri->segment($last);
/**
* Do whatever logic you need to do to calculate your data
*/
// ...
/**
* Load the view
*/
$this->load->view( 'attendance/' . $lastSegment, $data );
This could probably be better architected using the CI routes capability though. For instance, if you have several view folders and view files within, it would be best practice to organize those and better cement your URI structures so that each URI segment plays a specific role:
CI routes.php
$route["vtp/(:any)/(:any)"] = "path_to_method";
Method
$dir = $this->uri->segment(2);
$view = $this->uri->segment(3);
$this->load->view( $dir . "/" . $view, $data );

Passing get variable in CodeIgniter

How to pass get variable from my view to the controller and to the model also and load to my view again
without the use of form like
$jcid= $row['id']; // this id from other table which is parent.
$s = "SELECT * FROM `jobs` WHERE job_cat=$jcid";
$re = mysql_query($s);
$no = mysql_num_rows($re);
echo $no;
Thanks in advance
Amit
Instead of using get param use like this
This can be your form url
http://example.com/index.php/news/local/metro/crime_is_up
$this->uri->segment(3); // Will give you news
Like wise in place of 3 replace with 4 will give you metro and so on. You can access this in controller.
Uri class in the codeigniter
http://ellislab.com/codeigniter/user-guide/libraries/uri.html
First use
$this->load->helper('url');
And then
$data['$jcid'] = $this->uri->segment(3);

Header Location with variable

How to go with this url localhost/pitch/action/task/1 ?
1 = pitch id
please answer this. thank you
this is my code controller.
public function insert_task(){
$this->load->model("save");
$data['pitch_id'] = $this->input->post('pitch');
$data['date'] = $this->input->post('date');
$data['name'] = $this->input->post('name');
$data['description'] = $this->input->post('description');
$task = $this->save->insert_task_to_db($data);
if($task){
header('location:'.base_url()."action/task".$this->index());
}
}
You can use
redirect('action/task/'.$this->index(),'refresh');
this code will reload the page and redirect to the desired url.
Please let me know if you face any problem.
codeigniter provides redirect, like:
redirect( base_url() . 'action/task/' . $this->index() );

Calling controllers dynamically

I'm attempting to create dynamic routing in Laravel for my controllers - I know this can be done in Kohana, but I've been unsuccessful trying to get it working with Laravel.
This is what I have right now:
Route::get('/{controller}/{action?}/{id?}'...
So I would like to call controller/method($id) with that.
Ideally this is what I would like to do:
Route::get('/{controller}/{action?}/{id?}', $controller . '#' . $action);
And have it dynamically call $controller::$action.
I've tried doing this:
Route::get('/{controller}/{action?}/{id?}', function($controller, $action = null, $id = null)
{
$controller = new $controller();
$controller->$action();
});
But I get an error message: Class Controller does not exist.
So it appears that Laravel is not including all the necessary files when the controller extends the BaseController.
If I use $controller::$action() it tells me I can't call a non-static function statically.
Any ideas for how to make this work?
You can auto register all controllers in one fell swoop:
Route::controller( Controller::detect() );
If you're using Laravel 4 (as your tag implies), you can't use Controller::detect() anymore. You'll have to manually register all the controllers you want to use.
After reading that Laravel doesn’t support this anymore, I came up with this solution:
$uri = $_SERVER['REQUEST_URI'];
$results = array();
preg_match('#^\/(\w+)?\/?(\w+)?\/?(\w+)?\/?#', $_SERVER['REQUEST_URI'], $results);
// set the default controller to landing
$controller = (empty($results[1])) ? 'landing' : $results[1];
// set the default method to index
$method = (empty($results[2])) ? 'index' : $results[2];
Route::get('{controller?}/{action?}/{id?}', $controller . '#' . $method);
// now we just need to catch and process the error if no controller#method exists.

Resources