Welcome Guest, Not a member yet? Register   Sign In
How to call function from custom helper ?

On codeigniter 4.3.7 site I need to create a custom helper so I created a file app/Helpers/helper.php with code:

PHP Code:

namespace App\Helpers;

DATE_FORMAT '%B %d, %Y';

formatDateTime($DateTimeLabel ''$format '')

I try to call this method from view file app/Views/admin/categories/index.php:

PHP Code:
<?php helper('helper'); ?>
<?= $this

<?= $this->section('content'?>

<td><?= formatDateTime($category['created_at'], "ASTEXT"?></td> 

But I got error that function formatDateTime not found even after in app/Config/Autoload.php I added ref to my helper file :

PHP Code:
public $helpers = [

Have I to run some console commands to use my helper ?

Thanks in advance!

(This post was last modified: 10-02-2023, 07:34 AM by JustJohnQ.)

rename your file to i.e. myDate_helper. Save it in the App\Helpers folder.
I don't think it is necessary to namespace the file, I usually don't do that.

Before calling the method formatDateTime(), add the following line before calling it:
PHP Code:
Now you can call your method by using:
PHP Code:
$test formatDateTime($params); 

Also check out: https://stackoverflow.com/questions/6188...eigniter-4

Sadly, I could not have found that solution in the documentation. It shall be explained more clearly. ( for example, I could not have found anything about the suffix name_helper.php).

So you can use the above solution or add your HELPER FUNCTION to the BaseController


* An array of helpers to be loaded automatically upon
* class instantiation. These helpers will be available
* to all other controllers that extend BaseController.
* @var array
protected $helpers = ["form", "test"];

See https://codeigniter4.github.io/CodeIgnit...g-a-helper


Just remove namespace from helper - //namespace App\Helpers;

And best practice use function wrapper in helpers files
if(!function_exists('formatDateTime')) {
  function formatDateTime() {

(12-04-2023, 02:35 PM)kenjis Wrote: See https://codeigniter4.github.io/CodeIgnit...g-a-helper

You are right, there is some information. But, I am a beginner and it isn't easy to understand. It shall be stated clearly that the file has to have the suffix _helper.php

It is my feedback, hopefully, helpful a bit to improve the readability of documentation.

@AlexSchneider I sent a PR to improve the docs. https://github.com/codeigniter4/CodeIgniter4/pull/8294
Can you review?

Theme © iAndrew 2016 - Forum software by © MyBB