Is it possible to call a function which is located in a controller from a view?
This is what i have in my controller, as an example
function checkKey
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
This way is smooth.
@controller method
$obj = array();
$obj['fnc'] = function(){ return 'hello'; };
$this->load->view( 'your_path', $obj );
@view
echo $fnc();
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');.
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
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
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
}