I created a controller named Api.php then I extended the Rest_Controller. I noticed that I can only use index_get() when creating a function in this controller
<?php
class Api extends REST_Controller{
public function __construct()
{
parent::__construct();
}
public function index_get(){
$car_id = $this->get('car_id');
if(!$car_id){
$this->response("No Car ID specified", 400);
exit;
}
$result = $this->model_getvalues->getCars( $car_id );
if($result){
$this->response($result, 200);
exit;
}
else{
$this->response("Invalid Car ID", 404);
exit;
}
}
}
but when I try creating my desired function like getAllCars() instead of index_get() I get an error message telling me unknown function.
How can I define my own function instead of using index_get() when using rest api library in CodeIgniter?
Thanks i have been able to figure it out, i just found out that the name before the _get is what matters to the url i.e when one has a method like getCars_get, you will have to call it using just getCars without the _get attach to it, it work for me. it means that one can have more than _get method in the API controller.
By default on https://github.com/chriskacerguis/codeigniter-restserver#handling-requests the method is index_get(),another way to use your own method is play with the HTTP GET parameter
ex:
if($this->get('car_id') == 'all'){
//your own function here
}
Or if you really want to create your own method you can refer on this http://programmerblog.net/create-restful-web-services-in-codeigniter/
All you have to do is change function index_get() to getAllCars_get(),
`<?php
class Api extends REST_Controller{
public function __construct()
{
parent::__construct();
}
public function getAllCars_get(){
//your code
}
}
?>
`
Like this
Related
Hello developers i am getting error but don't know why? All thing is correct i think so.
I am doing just simple delete in codeigniter using id.
Just check my code.
This is my controller.
public function deletecourse(){
$id = $this->uri->segment(4);
$elete = array(
'table'=>'ls_courses',
'where'=>array('id'=>$id)
);
$result=$this->coursemodel->deletecour($elete);
if($result){
$this->session->set_flashdata('success', 'Successfully deleted.');
}
else{
$this->session->set_flashdata('warning', 'Unable to delete data.Please try again.');
}
redirect(base_url().'admin/course/index/');
}
This is Model function.
class CourseModel extends CI_Model
{
public function __construct()
{
parent::__construct();
}
public function deletecour($elete)
{
$this->db->where($elete['where']);
return $this->db->delete($elete['table']);
}
public function fetchCourseByParentID($id)
{
$this->db->select('course_name, image, sort_order, parent_id,
date_added, status');
$this->db->from('ls_courses');
$this->db->where('id = ' . $id);
$query = $this->db->get();
if(!empty($query->result_array()))
{
return $query->result_array();
}
else
{
return $this->db->error();
}
}
}
Hello Guys first of all thank you because you all replied very frequently to my question. I found the problem of my code.
In my autoload.php i had passed the
$autoload['model'] = array('coursemodel','admin/coursemodel');
These are two different model but one for website and 2nd for admin side.
So when i was calling the model name. Problem is here with my model name which was clashing or you can say outside model was calling which is not for admin and there was no method named such as deletecour($elete).
So, that's why error was coming.
Thanks for your replies and sorry for wasting your time for this silly mistake.
$this->coursemodel->deletecour($elete);
at your model ...
name of your class is camel case.. in codeigniter documentation .. i have read somewhere to use underscore for naming classes with first later as capital ... change your model name from CourseModel to Course_model and try...
i dont know why it is happening ... but try to get all method available in your class... so you can find that ... why you are not able to call your method at model...
get all method available in your model
class CourseModel extends CI_Model
{
public function __construct()
{
parent::__construct();
var_dump(get_class_methods($this));
EXIT;
}
}
How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>
I am having problems with my code. When I try to debug my web application I get the following error message....Call to a member function find() on a non-object.....here is my code
class TeamsController extends AppController {
var $name = 'Teams';
function index() {
$this->set('teams', $this->team->find('all'));
}
function Welcome() {
}
}
I am trying to display records from my MySQL database. Now with that said, I did this tutorial and I followed the instructions down to the tee.....but somehow my code has bugs. The only difference between my code and the code of the tutorial I did is the variable names...and the controller names....and the I dont have the hello world function... Here is a sample of the code from the tutorial I did....
class PostsController extends AppController {
var $name = 'Posts';
function index() {
$this->set('posts', $this->Post->find('all'));
}
function hello_world() {
}
}
With that said, am I suppose to declare an instance of an object to get this to work?
It's likely a case sensitivity issue:
function index() {
$this->set('teams', $this->Team->find('all'));
}
If not, ensure your controller has access to the Teams model (e.g. $uses).
How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.
You can call controller function from view in the following way:
Controller:
public function read() {
$object['controller'] = $this;
$this->load->view('read', $object);
}
View:
// to call controller function from view, do
$controller->myOtherFunct();
Codeigniter is an MVC (Model - View - Controller) framework. It's really not a good idea to call a function from the view. The view should be used just for presentation, and all your logic should be happening before you get to the view in the controllers and models.
A good start for clarifying the best practice is to follow this tutorial:
https://codeigniter.com/user_guide/tutorial/index.html
It's simple, but it really lays out an excellent how-to.
I hope this helps!
You can call a controller function with AJAX on your view.
In this case, I'm using the jQuery library to make the call.
<script type="text/javascript">
$.ajax({
url: "<?=site_url("controller/function")?>",
type: "post", // To protect sensitive data
data: {
ajax:true,
variableX: "string",
variableY: 25
//and any other variables you want to pass via POST
},
success:function(response){
// Handle the response object
}
});
</script>
This way you can create portions of code (modules) and reload them the AJAX method in a HTML container.
I would like to answer this question as this comes all times up in searches --
You can call a controller method in view, but please note that this is not a good practice in any MVC including codeigniter.
Your controller may be like below class --
<?php
class VCI_Controller extends CI_Controller {
....
....
function abc($id){
return $id ;
}
}
?>
Now You can call this function in view files as below --
<?php
$CI =& get_instance();
$CI->abc($id) ;
?>
class MY_Controller extends CI_Controller {
public $CI = NULL;
public function __construct() {
parent::__construct();
$this->CI = & get_instance();
}
public function yourMethod() {
}
}
// in view just call
$this->CI->yourMethod();
Try this one.
Add this code in Your View file
$CI = & get_instance();
$result = $CI->FindFurnishName($pera);
Add code in Your controller File
public function FindFurnishName($furnish_filter)
{
$FindFurnishName = $this->index_modal->FindFurnishName($furnish_filter);
$FindFurnishName_val = '';
foreach($FindFurnishName as $AllRea)
{
$FindFurnishName_val .= ",".$AllRea->name;
}
return ltrim($FindFurnishName_val,',');
}
where
FindFurnishName is name of function which is define in Your Controller.
$pera is a option ( as your need).
One idea i can give is,
Call that function in controller itself and return value to view file. Like,
class Business extends CI_Controller {
public function index() {
$data['css'] = 'profile';
$data['cur_url'] = $this->getCurrURL(); // the function called and store val
$this->load->view("home_view",$data);
}
function getCurrURL() {
$currURL='http://'.$_SERVER['HTTP_HOST'].'/'.ltrim($_SERVER['REQUEST_URI'],'/').'';
return $currURL;
}
}
in view(home_view.php) use that variable. Like,
echo $cur_url;
views cannot call controller functions.
I know this is bad..
But I have been in hard situation where it is impossible to put this back to controller or model.
My solution is to call a function on model.
It can be do inside a view.
But you have to make sure the model has been loaded to your controller first.
Say your model main_model, you can call function on the model like this on your view :
$this->main_model->your_function();
Hope this help. :)
We can also pass controller function as variable in the view page.
class My_controller extends CI_Controller {
public function index() {
$data['val']=3;
$data['square']=function($val){
return $val*$val;
};
$this->load->view('my-view',$data);
}
}
In the view page
<p>Square of <?=$val?>
<?php
echo $square($val);
?>
</p>
The output is 9
it is quite simple just have the function correctly written in the controller class and use a tag to specify the controller class and method name, or any other neccessary parameter..
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Iris extends CI_Controller {
function __construct(){
parent::__construct();
$this->load->model('script');
$this->load->model('alert');
}public function pledge_ph(){
$this->script->phpledge();
}
}
?>
This is the controller class Iris.php
and the model class with the function pointed to from the controller class.
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Script extends CI_Model {
public function __construct() {
parent::__construct();
// Your own constructor code
}public function ghpledge(){
$gh_id = uniqid(rand(1,11));
$date=date("y-m-d");
$gh_member = $_SESSION['member_id'];
$amount= 10000;
$data = array(
'gh_id'=> $gh_id,
'gh_member'=> $gh_member,
'amount'=> $amount,
'date'=> $date
);
$this->db->insert('iris_gh',$data);
}
}
?>
On the view instead of a button just use the anchor link with the controller name and method name.
<html>
<head></head>
<body>
PLEDGE PH
</body>
</html>
I had this same issue , but after a couple of research I fond it out it's quite simple to do,
Locate this URL in your Codeigniter project: application/helpers/util_helper.php
add this below code
//you can define any kind of function but I have queried database in my case
//check if the function exist
if (!function_exists('yourfunctionname')) {
function yourfunctionname($param (if neccesary)) {
//get the instance
$ci = & get_instance();
// write your query with the instance class
$data = $ci->db->select('*');
$data = $ci->db->from('table');
$data = $ci->db->where('something', 'something');
//you can return anythting
$data = $ci->db->get()->num_rows();
if ($data > 0) {
return $data;
} else {
return 0;
}
}
}
I know this question is old but it is still a relevant question. From my experience there are situations that warrant calling a function from view in your Codeigniter 4 app, I'll just advise that you keep it clean and minimal. Below is how I have called controller function from view:
In your controller file add this code
public function index()
{
$data = [];
$model = new UsersModel();
$data['users'] = $model->findAll();
// $this refers to the controller to be called from view
$data['callfromview'] = $this;
return view('users', $data)
}
In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>
Finally in the controller, create the fetch_data function
public function fetch_data($id)
{
$image = new ImageModel();
return $image->find($id);
}
the END!
if you need to call a controller from a view,
maybe to load a partial view,
you thinking as modular programming,
and you should implement HMVC structure in lieu of plane MVC.
CodeIgniter didnt implement HMVC natively,
but you can use this useful library in order to implement HMVC.
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc
after setup
remember:that all your controllers should extends from MX_Controller in order to using this feature.
Go to the top of your View code and do it like this :
<?php
$this->load->model('MyModelName');
$MyFunctionReturnValue = $this->MyModelName->MyFunctionName($param));
?>
<div class="row">
Your HTML CODE
</div>
here's an example of url:
http://www.example.com/search/search-keyword
I am trying to make this work, I removed the index.php using .htaccess, search is the controller and I want to pass a parameter in the index method.
this is currently what it looks like:
class Search extends CI_Controller{
function index($param){
echo $param;
}
}
any suggestions? I can't seem to make it work
You need the index segment http://www.example.com/search/index/search-keyword.
Or you need to use a route $route['search/(:any)'] = 'search/index/$1';
Or you can look at remap
Remember not to trust user input, especially when you are throwing it into your url. The latest version of CI supports $_GET variables now, so you may want to look into using that or flashdata. A searh term as simple as O' Brien will give you a fatal error ("The URI you submitted has disallowed characters.").
class Search extends CI_Controller{
function _remap($param) {
$this->index($param);
}
function index($param){
echo $param;
}
}
You should then be able to access that as: /search/123123 :and the page would echo out "123123" or whatever you put in place of that.
function _remap($parameter){
$this->_index($parameter);
}
Give it a try and tell us how it went.
Most of these solutions will only work if you only have a single function called index() in your controller. If you have this in your routes:
$route['search/(:any)'] = 'search/index/$1';
With the above in your routes, what will happen is that your search function will work but then if you add any other functions to that same controller they'll all be redirected to /search/index/$1.
The only solution I can think of that allows you to use the URL you want while still being able to add any other functions to your search controller is to add a sort of messy conditional to your routes file. Here's what it will look like and what it does:
$request = $_SERVER['REQUEST_URI']; // Only add this for readability
if(!strpos($request, 'search/another_function') || !strpos($request, 'search/more_functions')) {
$route['search/(:any)'] = 'search/index/$1';
}
What this is doing is basically saying "if the requested URL doesn't contain the name of any of my search controller functions then it must be meant for the index so we'll activate the route rule for index".
This will allow you to take requests for search/any_other_functions_you_have without issue and only activate the rule for hiding the index function when a request URI doesn't match any of them.
One side effect of this is that you'll never get a 404. For example, if someone enters a URL like "yourdomain.com/search/something" and they expect it to show a non-search result page they won't get a 404 alerting them to the fact that there is no page like that and instead the app will assume what they typed is a search term. However, it sounds like this isn't much of an issue for you and I don't see it being such a terrible thing for one controller to be unabe to return 404s.
You need to understand the way code igniter urls work, its basically like this:
http://www.mysite.com/{controller}/{function}
So what your url is actually looking a function called "keyword" in your search controller.
You have multiple options. The easiest will be to simply change the url to:
http://www.mysite.com/search/result/keyword
Then this should work perfectly:
class Search extends CI_Controller{
function result($param){
echo $param;
}
}
If you really want to use the url as you had it, you can use the same snippet of code as above but also open up "application/config/routes.php" and add this to the bottom.
$route['search/(:any)'] = "search/result";
Alternatively if you want to continue using the index function you can change it to this
$route['search/(:any)'] = "search/index";
And change your class to something like this:
class Search extends CI_Controller{
function index($param=FALSE){
if($param == FALSE) {
//Show search box
} else {
//Show search results
}
}
}
Don't forget to update your answer if you figure it out yourself or accept somebodies answer if it answers it :)
I've just started CI and here was my solution and implemented it on my website. So far it works for me and my search queries have been indexed by google as links
Class Search extends CI_Controller{
function index(){
$search_item = $this->input->post('search_box'); // this is from the input field
redirect(base_url()."search/q/".url_title($search_item));
}
// i've redirected it to the "search" controller then :
function q($search_item = null){// process search
// load the view here with the data
}
}
This is my solution:
From CI userGuide
public function _remap($method)
{
if ($method == 'some_method')
{
$this->$method();
}
else
{
$this->default_method();
}
}
So I've created my controller in this way:
class Shortener extends CI_Controller {
function shortener() {
parent::__construct();
}
function index($getVar) {
echo "Get var: " . $getVar;
}
function config() {
echo "another function";
}
function _remap($method) {
if($method == "config") {
$this->$method();
}
else {
$this->index($method);
}
}
}
Hope this can be helpful to someone...
BUG: if you call /shortener _remap function pass "index" to index() function...it can be solved adding an if condition or something else
You should use the CI URI Class. http://codeigniter.com/user_guide/libraries/uri.html
class Search extends CI_Controller{
function index($param){
//echo the search-keyword
echo $this->uri->segment(2);
}
}
This easiest way is just to use uri segments:
class Search extends CI_Controller{
function index(){
$param=$this->uri->segment(2);
echo $param;
}
}
Or like Madmartigan said, use routes, which is probably the better way of doing this.
I had to also check if some variable was passed or not - so here is the solution that I took.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Story extends CI_Controller{
function story() {
parent::__construct();
}
function _remap($parameter){
$this->_index($parameter);
}
public function _index($story_id) {
if($story_id == 'index'){
//No variable passed
redirect('auth', 'refresh');
}else{
$data['title'] = "Story";
$this->load->view('story', $data);
}
}
}
Hope this helps someone!
Thank you. This code works for me. If parameter is a number
Or you need to use a route $route['search/(:any)'] = 'search/index/$1';
However, If the parameter is a string (http://[::1]/note/getnote/index/fg => http://[::1]/note/getnote/fg). I use _remap() like this code.
<?php
class Getnote extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('image_lib');
}
public function index(){
}
public function _remap($keyname)
{
$this->load->model('Laydb');
$data = $this->Laydb->getNote($keyname);
$proListArray['patitle'] = "Edit notepad";
$this->load->view('top', $proListArray);
$this->load->view('editblog', $data);
$this->load->view('bottom');
}
}
class Search extends CI_Controller{
function index($param){
echo $param;
}
}
In routes.php
$routes['search/(:any)'] = 'search/index/$1';
It's all
I finally found a workaround since I cant simply put post variables into the URL.
What I did was create another function, then redirect it to that function.
class Search extends CI_Controller{
function index(){
$search_item = $this->input-post('search_item');
redirect("search/q/".url_title($search_item));
}
function q($key){
// process search
}
}