CodeIgniter - Calling a function from inside a view

后端 未结 7 1481
长情又很酷
长情又很酷 2021-01-06 13:25

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         


        
相关标签:
7条回答
  • 2021-01-06 14:03

    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

    0 讨论(0)
  • 2021-01-06 14:05

    This way is smooth.

    @controller method
    $obj = array();
    $obj['fnc'] = function(){ return 'hello'; };
    $this->load->view( 'your_path', $obj );
    
    @view
    echo $fnc();
    
    0 讨论(0)
  • 2021-01-06 14:07

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

    0 讨论(0)
  • 2021-01-06 14:07

    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

    0 讨论(0)
  • 2021-01-06 14:12

    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

    0 讨论(0)
  • 2021-01-06 14:20

    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
    }
    
    0 讨论(0)
提交回复
热议问题