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

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:
<?php

namespace App\Helpers;

const 
DATE_FORMAT '%B %d, %Y';

function 
formatDateTime($DateTimeLabel ''$format '')
{
... 

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

PHP Code:
<?php helper('helper'); ?>
<?= $this
->extend("layouts/default"?>

<?= $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 = [
'app/Helpers/helper.php'
]; 

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

Thanks in advance!
Reply
#2

(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:
helper('myDate'); 
Now you can call your method by using:
PHP Code:
$test formatDateTime($params); 

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

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

example

/**
* 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"];
Reply
#4

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

Hi

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

And best practice use function wrapper in helpers files
Code:
if(!function_exists('formatDateTime')) {
  function formatDateTime() {
  }
}
Reply
#6

(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.
Reply
#7

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




Theme © iAndrew 2016 - Forum software by © MyBB