Codeigniter can't use this->uri->segment(3) as value in function - codeigniter

Why this code is ok
$this->sch_teacher_id = $this->ion_auth->user_by_username("vika")->row()->id;
But this doesn't work?
$this->sch_teacher_id = $this->ion_auth->user_by_username($this->uri->segment(3))->row()->id;
My url is domain:8888/admin_schedule/teacher/vika
route.php contains
$route['admin_schedule/teacher/(:any)'] = "admin_schedule/index/$1";
I use code lines in function __construct(), and the result of it use in another controller function, because 3 functions use this result. If I move this code in one of this functions and use $this->uri->segment(3) then I get not 'vika's lessons, but my own lessons, so
public function user_by_username($username = FALSE)
{
$this->trigger_events('user');
//if no id was passed use the current users id
$username || $username = $this->session->userdata('username');
$this->limit(1);
$this->where($this->tables['users'].'.username', $username);
$this->users();
return $this;
}
works good. But $this->uri->segment(3) if use it as parameter in user_by_username function, doesn't work!
page generated next way:
controller admin_schedule have function index which render view index.php.
And in that view I use javascript, that call another function from admin_schedule controller = get_schedule_db_recurring_events_on_daysweek such way:
...
{
url: '/admin_schedule/get_schedule_db_recurring_events_on_daysweek/',//"<?echo $data_path?>",
backgroundColor: 'red',
}
and in controller
function get_schedule_db_recurring_events_on_daysweek()
{
$start = date('Y-m-d H:i', $this->input->get('start'));
$end = date('Y-m-d H:i', $this->input->get('end'));
$sch_teacher_id = $this->uri->segment(3); // <--- this doesn't work, but $sch_teacher_id = 111 works perfectly
$result=$this->Schedule_model->get_schedule_recurring_events_on_daysweek($start, $end, $sch_teacher_id);
$count=count($result);
if($count>0){
echo json_encode($result);
}
}
Please, help understand this problem.

I can't remember the reason - it's just CI quirk you have learn to accept - you can't use $this->uri->segment(3) etc as an argument directly, you will need to assign it and then pass that as #almix suggested for his sanity test.
At-least I have also always had trouble using it directly as an argument - tho I will be happy for anyone to correct me!

I solved my problem!
Think that something goes wrong because of ajax calls. So when I code in controller
function __construct()
{
parent::__construct();
...
$this->sch_teacher_row = $this->ion_auth->user_by_username($this->uri->segment(3))->row();
$this->data['sch_teacher_id'] = $this->sch_teacher_row->id;
$this->data['subtitle'] = $this->sch_teacher_row->username;
}
Next I have the right value ('vika'), or to be more precise vika's id ('911') in view file but not in other function of my controller. But I can pass this value now (sch_teacher_id) from the view to this controller with jQuery $.ajax option data:
eventSources: [
...
{
url: '/admin_schedule/get_schedule_db_recurring_events_on_daysweek/',//"<?echo $data_path?>",
type: 'GET',
data: {sch_teacher_id: sch_teacher_id},
backgroundColor: 'red',
}
],
And next (on the other side of the mountain) catch this GET parameter and kick it to the model function:
function get_schedule_db_recurring_events_on_daysweek()
{
...
$sch_teacher_id_from_view = $this->input->get('sch_teacher_id');
$result=$this->Schedule_model->get_schedule_recurring_events_on_daysweek($start, $end, $sch_teacher_id_from_view);
...
}
And it is all the breakdance.

Related

conditional nested routes in laravel

I want to check segment of particular URL on route and based on value of segment decide it to handle to another route.Somewhat like below:
Route::get('{module}/{seg}', function(){
if (is_numeric((Request::segment(3)) {
return Route::get('{module}/{seg}',Request::segment(2) . 'Controller#index');
}else{
return Route::get('{module}/{seg}',Request::segment(2).'Controller#index' . Request::segment(3));
}
});
I don't think above code works but can anyone suggest a working code for implementing above logic in laravel?
I'd suggest adding it as an optional parameter, and handle differences in the controller. Given your code, it might look like this, for instance:
// route
Route::get('{module}/{seg}/{param?}', 'Controller#index');
// controller
public function index($module, $seg, $param = null)
{
// for dynamic index methods
if (is_numeric($param)) {
$method = 'index' . $param;
return $this->{$method}();
}
// for non-numeric third-segment params, continue here as usual
}

Missing argument 1 in laravel controller

In routes.php I have following route
Route:: get('/crm/hotel/occupant/{id}', array('uses'=>'OccupantController#occupant','as'=>'crm.hotel.occupant'));
for the above route ... if i put the controller like this it's work...but if i remove the $room_id in model calling like
$hotel = new Occupant();
.. i got an error missing argument 1 ....
public function occupant($room_id)
{
$hotel = new Occupant($room_id);
// manage page
return $hotel->occupant($room_id);
}
how to solve it ...
You can make {id} optional.
It is achieved by this:
Route:: get('/crm/hotel/occupant/{id?}', array('uses'=>'OccupantController#occupant', 'as'=>'crm.hotel.occupant'));
as explained by #vinweb you have to add a question mark ? to your id parameter,
Route:: get('/crm/hotel/occupant/{id?}', array('uses'=>'OccupantController#occupant','as'=>'crm.hotel.occupant'));
but you also have to set your variable to a default value (example taken from the official doc,):
Route::get('user/{id}', function ($id) {
return 'User '.$id;
});
So, in your case it would be probably be something like this :
public function occupant($room_id = null)
{
$hotel = new Occupant($room_id);
// manage page
return $hotel->occupant($room_id);
}

handling database error with ajax request codeigniter

I am intentionally making error i.e. using one of the coulmn's name wrong to learn how to handle the error with ajax call with codeigniter.
Last Comment in controller function at the end is my question/problem
My AJX Code is following. I am using ajaxform plugin. It shows me all response from controller perfectly but problem is only I am unable to get response from model in controller while using ajax call that is little weird
$('#myForm').ajaxForm
({
success: function(responseText)
{
if(responseText != "1")
$('#feedback').html(responseText);
}
});
Following is snapshot of exact error which i can see in console but unable to get in controller and hence in view. It describes complete error i.e unknown column in given query, but i captured only upper portion.
My model function is below
public function updateItem($id, $data, $tbl)
{
$this->db->where('id', $id);
$r = $this->db->update($tbl, $data);
if($r)
return $r;
else
{
$r = $this->db->_error_message();
return $r;
}
}
My controller function code
public function upadteme()
{
$r = $this->ajax_model->updateItem($uid, $data, 'users');
echo $r." -- "; // Unable to get this echo working
//when using ajaxcall (calling controller through ajax) otherwise fine
}
It looks like the class will not populate _error_message if db_debug is on which it appears to be by default.
In config/database.php, set
$db['default']['db_debug'] = FALSE;
and try again.

Loading page dynamically from database via id in controller

I am trying to load a page dynamically based on the database results however I have no idea how to implement this into codeigniter.
I have got a controller:
function history()
{
//here is code that gets all rows in database where uid = myid
}
Now in the view for this controller I would like to have a link for each of these rows that will open say website.com/page/history?fid=myuniquestring however where I am getting is stuck is how exactly I can load up this page and have the controller get the string. And then do a database query and load a different view if the string exsists, and also retrieve that string.
So something like:
function history$somestring()
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
What I don't understand is how I can detect if $somestring is at the end of the url for this controller and then be able to work with it if it exists.
Any help/advice greatly appreciated.
For example, if your url is :
http://base_url/controller/history/1
Say, 1 be the id, then you retrieve the id as follows:
function history(){
if( $this->uri->segment(3) ){ #if you get an id in the third segment of the url
// load your page here
$id = $this->uri->segment(3); #get the id from the url and load the page
}else{
//here is code that gets all rows in database where uid = myid and load the listing view
}
}
You should generate urls like website.com/page/history/myuniquestring and then declare controller action as:
function history($somestring)
{
if($somestring){
//I will load a different view and pass $somestring into it
} else {
//here is code that gets all rows in database where uid = myid
}
}
There are a lot of ways you can just expect this from your URI segments, I'm going to give a very generic example. Below, we have a controller function that takes two optional arguments from the given URI, a string, and an ID:
public function history($string = NULL, $uid = NULL)
{
$viewData = array('uid' => NULL, 'string' => NULL);
$viewName = 'default';
if ($string !== NULL) {
$vieData['string'] = $string;
$viewName = 'test_one';
}
if ($uid !== NULL) {
$viewData['uid'] = $uid;
}
$this->load->view($viewName, $viewData);
}
The actual URL would be something like:
example.com/history/somestring/123
You then know clearly both in your controller and view which, if any were set (perhaps you need to load a model and do a query if a string is passed, etc.
You could also do this in an if / else if / else block if that made more sense, I couldn't quite tell what you were trying to put together from your example. Just be careful to deal with none, one or both values being passed.
The more efficient version of that function is:
public function history($string = NULL, $uid = NULL)
{
if ($string !== NULL):
$viewName = 'test_one';
// load a model? do a query?
else:
$viewName = 'default';
endif;
// Make sure to also deal with neither being set - this is just example code
$this->load->view($viewName, array('string' => $string, 'uid' => $uid));
}
The expanded version just does a simpler job at illustrating how segments work. You can also examine the given URI directly using the CI URI Class (segment() being the most common method). Using that to see if a given segment was passed, you don't have to set default arguments in the controller method.
As I said, a bunch of ways of going about it :)

Laravel: redirect to another controller which requires POST variables

I have ReportController
Index which is routed as POST only
public function index() // must have start, end, client
{
$start = Input::get('start'); // <<< This are POST variables
$end = Input::get('end'); // <<< This are POST variables
$client = Input::get('client'); This are POST variables
db request... output view..
}
when I click "delete row", it post info to
public function deleteRow()
{
db request -> delete();
//How do I go back to index controller and pass same $_POST['start'],$_POST['end'],$_POST['client']
}
How do I go back to index controller and pass same $_POST['start'],$_POST['end'],$_POST['client']?
You might be able to use Redirect::to('url')->withInput()
Then you can use Input::get('key')
If that doesn't work, try Input::old('key') -> Less pretty
Your post variables are no longer available once you make another request to the deleteRow method from the view, so you have to pass those variables to the deleteRow method. You build a view/ui from your index method like
public function index() // must have start, end, client
{
$start = Input::get('start');
$end = Input::get('end');
$client = Input::get('client');
db request... output view.. // <-- Outputs view with "delete row" link
}
Hope, you pass those post variables in this view, if not then pass those variables to this view and build the delete row link with these variables, something like
"ReportController/deleteRow/$start/$end/$client" // just an idea
Which means, your deleteRow method now should look like (also make changes in the routing of this)
public function deleteRow($start, $end, $client)
{
// db request -> delete();
return Redirect::to('index')
->with('postVars', array('start' => $start, '$end' => $end, 'client', $client));
}
So, it's clear that you have to pass those variables to the deleteRow method and that's why deleteRow methods route should be reconstructed according to the params. So, finally, your index method should look like
public function index() // must have start, end, client
{
$postVars = session::has('postVars') ? session::get('postVars') : Input:all();
$start = $postVars['start'];
$end = $postVars['end'];
$client = $postVars['client'];
db request... output view..
}

Resources