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'm a newbie in CodeIgniter. I want to use the following function and needs to be run in every page. I'm calling the function in the top header of the view. Even though different subviews are loaded in the content below, the navigation bar should load this function in order to count notifications and messages on every run.
function count_records_in_table($table, $where)
{
$this->db->select('count(id) as rows');
$this->db->from($table);
$this->db->where($where);
$query = $this->db->get();
foreach($query->result() as $r)
{
return $r->rows;
}
}
first create the common model
then put this function on it and load this model in
$autoload['model'] = array('mdl_common');
autoload file in config
finally you can use your function by calling model common like this
$this->mdl_common->count_records_in_table("table_name","where");
you can use in every page you want try it it will helps .
Here is suitable solution
First create one file say common.php in application/libraries/common.php
Now write below code in common.php file
class Common extends CI_Controller
{
public function customFailMessage($msg)
{
$xml = new SimpleXMLElement('<Response/>');
$xml->addChild('status','success');
$xml->addChild('msg',"my message");
print ($xml->asXML());
die;
}
}
Now call you function from any of your controller like this
class Ws_plan extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->library('common');
}
public function test()
{
$this->common->customFailMessage();
}
}
Hope you got idea how to use common function in all controller
Here is my controller code
public function index()
{
$this->load->model("mod_home");
$data['avoinics'] = $this->mod_home->getAvoinics();
$data['dir']="home";
$data['page']="index";
$this->load->view('main',$data);
}
for another page
public function about()
{
$this->load->model("mod_home");
$data['avoinics'] = $this->mod_home->getAvoinics();
$data['dir']="home";
$data['page']="about";
$this->load->view('main',$data);
}
But i don't want to send $data['avoinics'] again again. Is there any way to access a data from anypage.
How to use same data in a single view more than time.
foreach($avoinics as $avoinics):
$name=$avoinics->sc_name;
echo '<li>'.$name.'</li>';
endforeach;
if i use it again on same view page it's sowing error...
Yes, you can:
Create a global array
private $data = array();
In constructor
$this->load->model("mod_home");
$this->data['avoinics'] = $this->mod_home->getAvoinics();
Now your function will look like this
public function index() {
$this->data['dir']="home";
$this->data['page']="index";
$this->load->view('main',$this->data);
}
For second part, do not change the variable value
foreach($avoinics as $record){
echo '<li>'.$record['name'].'</li>';
}
$avoinics is intact now. You can use it again until you do not modify it.
A good example you might easily understand is when you need to call certain scripts or css files for a specific controller. You won't call it in every single page but yes in the constructor.
class yourController extends CI_Controller
{
private $data;
public function __construct()
{
$this->data['css'] = array('file1.css', 'file2.css');
$this->data['js'] = array('jquery.min.js', 'jquery-ui.min.js');
}
public function index()
{
$this->load->view('yourView', $this->data);
}
public function about()
{
$this->load->view('yourView', $this->data);
}
}
I recommend you to extend core ci_controller with my_controller and declare there your variable in constructor. Then in your new controllers extend your my_controller where you will have variable declaration.
I'm new to codeigniter and I have two controllers: utility.phpand welcome.php.
In utility.php, I have functions:
function getdata() {
//code here
}
function logdata() {
//code here
}
Inside welcome.php, I have this function:
function showpage() {
//some code here
//call functions here
}
What I want to do is inside my welcome.php, I want to call the functions from utility.php. How do I do this? Thanks.
Refrence from here
To extend controller please either follow this tutorial or see some code below.
differences between private/public/protected
make a file in folder /application/core/ named MY_Controller.php
Within that file have some code like
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Controller extends CI_Controller {
protected $data = Array(); //protected variables goes here its declaration
function __construct() {
parent::__construct();
$this->output->enable_profiler(FALSE); // I keep this here so I dont have to manualy edit each controller to see profiler or not
$this->load->model('some_model'); //this can be also done in autoload...
//load helpers and everything here like form_helper etc
}
protected function protectedOne() {
}
public function publicOne() {
}
private function _privateOne() {
}
protected function render($view_file) {
$this->load->view('header_view');
if ($this->_is_admin()) $this->load->view('admin_menu_view');
$this->load->view($view_file . '_view', $this->data); //note all my view files are named <name>_view.php
$this->load->view('footer_view');
}
private function _isAdmin() {
return TRUE;
}
}
and now in any of yours existing controllers just edit 1st or 2nd line where
class <controller_name> extends MY_Controller {
and you are done
also note that all your variables that are meant to be used in view are in this variable (array) $this->data
example of some controller that is extended by MY_Controller
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class About extends MY_Controller {
public function __construct() {
parent::__construct();
}
public function index() {
$this->data['today'] = date('Y-m-d'); //in view it will be $today;
$this->render('page/about_us'); //calling common function declared in MY_Controller
}
}
You don't is the short answer.
The point of MVC is to have your code well organized.
What you can do though is create a library in the libraries folder where you put methods you need in more than one controller.
For example you can make a mylog library, where you can put all your log related stuff. In any controller you will then call:
$this->load->library('mylog');
$this->mylog->logdata();
Besides functions that deal with data models should reside in models. You can call any model from any controller in CI
That is out of concept, if you want to call code in different controllers do following:
create helper and call function whenever (even in view) you want.
extend CI_Controller so you can use one or more functions in any controller that is extended.
Lets start with helper:
create file in folder application/helpers/summation_helper.php
use following sample of code
<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
function sum($a, $b) {
//$CI =& get_instance();
// if you want to use $this variable you need to get instance of it so now instead of using $this->load... you may use $CI->load
$return = $a + $b;
return number_format($return, 3);
}
If you are going to use your helper in many controllers/views please load it in autoload, otherwise just load it manualy $this->load->helper('summation');
Extending Controller_CI: this is way better approach if you are using database. Please follow this tutorial, which explains it all.
*I have crafted an answer just before site went down posting this from cellphone.
I am trying to get scroll news in any page of the website from database without having to pass the variable in every controller of the site. So I decided to use hooks instead of passing scroll variable in every controller.
I did create a class like this
class Scroll
{
function getScroller()
{
$data = array();
$CI =& get_instance();
$CI->db->where('a_status','active');
$CI->db->limit(4);
$CI->db->order_by('id','desc');
$Q = $CI->db->get('news');
if($Q->num_rows() > 0){
foreach($Q->result_array() as $row){
$data[] = $row;
}
}
$Q->free_result();
return $data;
}
}
What I get now is
Severity: Notice
Message: Trying to get property of non-object
Call to a member function get() on a non-object in E:\xampp\htdocs\
Can anyone please help me how to do this ? Thanks I want to get scrollernews in any controller's view automatically without having to pass in each controller. Thanks
If you are defining that on a view level, there is no need for that.
You can define db requests directly in a view.
Other approach would be to have separated controller which with separate view and load it in the page through iframe. It's often used for "web widgets" that can be later on loaded in to another pages.
Extending the core class of CI Controller will should cause you less troubles.
http://ellislab.com/codeigniter/user-guide/general/core_classes.html
application/core/MY_Controller.php
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
//By do this, all controllers who use this class as parent controller
//will have $news in their views
$this->load->vars(array(
'news' => array()
));
}
}
application/controller/welcome.php
class Welcome extends MY_Controller {
public function index()
{
$this->load->view('welcome_message');
}
}
application/views/welcome_message.php
var_dump($news);
use separated library or helper and call that method on controller's constructs like :
class My_Controller extends CI_Controller(){
function __construct(){
parent::__construct();
//load your library
//call your library method
}
}