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: <?php I try to call this method from view file app/Views/admin/categories/index.php: PHP Code: <?php helper('helper'); ?> 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!
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'); 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 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"];
Hi
Just remove namespace from helper - //namespace App\Helpers; And best practice use function wrapper in helpers files Code: if(!function_exists('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? |
Welcome Guest, Not a member yet? Register Sign In |