开发者

CodeIgniter - Calling a function from inside a view

Is it possible to call a function whi开发者_JAVA百科ch is located in a controller from a view?

This is what i have in my controller, as an example

function checkKeyExists($userid, $key){
}

Then inside my view i have the following

if(checkKeyExists($row->id, $role->key)){
}

But when I run it, it says that checkKeyExists is not defined.

If anyone can let me know how I could do this, that would be great.


Views are not meant to call controller actions. Reverse your logic, call that function in the controller and set it to a variable you sent to the view. Then you can have the if statement check that variable in your view template.

If that doesn't work for you, maybe a helper is what you need: https://www.codeigniter.com/user_guide/general/helpers.html


Like Widox said, I think a Helper is the best way out. Something like this:

<?php // test_helper.php
if(!defined('BASEPATH')) exit('No direct script access allowed');

function checkKeyExists($userid, $key, $table)
{
    $CI =& get_instance();

    $query = $CI->db->query("SELECT $keyFROM $table WHERE id = $userid LIMIT 1");
    if($query->num_rows() > 0)
    {
        return true;
    }else
    {
        return false; 
    }
}

?>

Then you can freely use on your views, just loading in your respective controllers like: $this->load->helper('test');.


Your controller should pass a set of data to your view.

Your view can then test if something is set and then act accordingly.

$this->data['my_setting']='value';
$this->load->vars($this->data);
$this->load->view('your_view');

Then in your view:

if(isset($my_setting)){
  do something with my_setting
}


you can declare a function this way inside views:

$myfunction = function_that_do_something( ) {
}

// then call as you want
$myfunction( );

the only thing is that you cannot acces the variables from the function -> simply pass them to the function


Controller:

public function xyz(){
   $data['controller'] = $this;
   $this->load->view('your_view_file',$data);
}  

View:

$controller->xyz();


Calling a controller function from view is not a good idea. it against the MVC role. But you can call the Model function from view. More answers about this question is vailable here


This way is smooth.

@controller method
$obj = array();
$obj['fnc'] = function(){ return 'hello'; };
$this->load->view( 'your_path', $obj );

@view
echo $fnc();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜