39

How to call codeigniter controller function from view? When i call the function in a controller, get a 404 page.

4
  • 3
    Can you explain what is your objective doing in that way? Commented Apr 3, 2012 at 3:18
  • The problem is fixed. The reason is in config base url setting Commented Apr 3, 2012 at 4:34
  • 1
    while I agree with comments below about this not being good MVC practice, this is still a good question, Commented Apr 3, 2012 at 16:17
  • you can write helpers for this Commented Jan 6, 2014 at 8:29

15 Answers 15

55

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();
Sign up to request clarification or add additional context in comments.

3 Comments

+1 because I knew the best method is to not call controllers in view, but knowing such tricks to break rules sometimes could be useful.
Another, simpler approach is to make the function static (i.e., public static function myOtherFunct() and call it from the view: ControllerName::myOtherFunct() No need to pass a class instance or anything else to the view.
Simpley awesome trick..
16

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!

6 Comments

For sure, I've already followed the tutorial with no result at all about this question.
Your link not available nowaday
How is this the acceptable answer? I could have gone to their page myself. We need to do better, friend.
Downvote since it is not a answer to the question. It can be very relevant to call a method in a controller from a view, in some cases.
Yea, there are plenty of good reasons to use functions in the view. Keep it simple and still presentation-related, but don't rule out functions completely.
|
11

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.

Comments

6

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) ;

?>

Comments

4
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();

Comments

4

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

  1. FindFurnishName is name of function which is define in Your Controller.
  2. $pera is a option ( as your need).

Comments

2

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;

1 Comment

Or can create model function then we can use in view file directly... $arr_fran = $this->reserv_model->experience_info($f['created_on']);
1

views cannot call controller functions.

2 Comments

@Anupama: Yes you can controllers from requests but not from views.
By the way , you can do it like: ControllerName::methodname();
1

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. :)

Comments

1

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

Comments

1

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>
        <a href="<?php echo base_url(); ?>index.php/iris/pledge_ph" class="btn btn-success">PLEDGE PH</a>
    </body>
</html>

Comments

1

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;
        }  
    }
}

1 Comment

Another, simpler approach is to make the function static (i.e., public static function myOtherFunct() and call it from the view: ControllerName::myOtherFunct() No need to pass a class instance or anything else to the view.
1

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:

  1. 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)
}
  1. In your view, call the controller like this:
<?php $something = $callfromview->fetch_data($id);?>

  1. Finally in the controller, create the fetch_data function

public function fetch_data($id)
{
    $image = new ImageModel();
    return $image->find($id);
}

the END!

Comments

0

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.

Comments

-1

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>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.