简体   繁体   中英

How to call function in controller from view in CodeIgniter?

My controller is like this :

public function index()
{
    $data_login = $this->session->userdata('login');
    $id = $data_login['customer_id'];

    $this->data['notification'] =  $this->get_data($id);    

    $this->load->view('notification/list_view', $this->data);
}

public function time_elapsed_string($datetime, $full = false) 
{
    ...
}

My view (list_view) is like this :

<table class="table table-striped table-advance table-hover">
    <tbody>
    <?php
        foreach ($notification as $key => $value) 
        {
    ?>

        <tr class="unread" data-messageid="1">
            <td class="view-message "> 
                <?php
                    echo '<a href='.base_url().'notification/notif/'.$value['notification_id'].'>'.$value['notification_message'].'</a><br>';
                ?>
            </td>
            <td class="view-message text-right"> <?php echo $this->time_elapsed_string($value['notification_created_date']); ?> </td>
        </tr>

    <?php
        }
    ?>
    </tbody>
</table>

When executed, there exist error like this :

Fatal error: Call to undefined method EX_Loader::time_elapsed_string().....

Seemed unable to call function time_elapsed_string in controller.

Any solution to solve my problem?

I believe, you can't use controller's method in view. You have to have helper function.

So, create a helper.php file then, make your function as below:

if ( ! function_exists('time_elapsed_string')){
    function time_elapsed_string($datetime, $full = false){
        // do your calculation 
        return 'something';
    }
}

Then include your helper.php file into your controller as below:

$this->load->helper('helper');

Now you will be able to use that "time_elapsed_string" function in your view.

you can't call $this function in view, you can use normal function and helper function.

best solution is use function in controller and use return value in view.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM