Cipr
Cipr

Reputation: 19

How to call custom functions in view page using Codeigniter

How can I call my own functions in view file using Codeigniter?

I have a function:

function hoursToSeconds ($hour) { // $hour must be a string type: "HH:mm:ss" $parse = array();

if (!preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$hour,$parse)) {
     // Throw error, exception, etc
     throw new RuntimeException ("Hour Format not valid");
}

 return (int) $parse['hours'] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'];

}

I just called function like this $sum += hoursToSeconds($rec['emp_late']);, but it didn't work.

What could be the issue here?

Upvotes: 0

Views: 2229

Answers (2)

Rahul Reghunath
Rahul Reghunath

Reputation: 1276

check the argument given to hoursToSeconds() is in correct format HH:mm:ss

Upvotes: 0

Akshay Hegde
Akshay Hegde

Reputation: 16997

The best way is to use helpers

https://www.codeigniter.com/userguide3/general/helpers.html

A CodeIgniter helper is a PHP file with multiple functions.

Lets create helper say hour_helper.php in application/helpers/, paste your function

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

if ( ! function_exists('hoursToSeconds'))
{
   function hoursToSeconds ($hour) { // $hour must be a string type: "HH:mm:ss"
    $parse = array();

    if (!preg_match ('#^(?<hours>[\d]{2}):(?<mins>[\d]{2}):(?<secs>[\d]{2})$#',$hour,$parse)) {
         // Throw error, exception, etc
         throw new RuntimeException ("Hour Format not valid");
    }

     return (int) $parse['hours'] * 3600 + (int) $parse['mins'] * 60 + (int) $parse['secs'];
  }
}

Load Helper

This can be in your controller, model or view (not preferable)

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

// to test 
echo hoursToSeconds('10:20:23');

If you want to share this helper across many module/controller/model then load automatically by adding it to the autoload configuration file i.e. path/to/application/config/autoload.php.

$autoload['helper'] = array('hour_helper');

In your case load helper in your controller, and then call it in your view

Upvotes: 2

Related Questions