CodeIgniter Forums
how load helper in a model? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: CodeIgniter 4 (https://forum.codeigniter.com/forum-28.html)
+--- Forum: CodeIgniter 4 Support (https://forum.codeigniter.com/forum-30.html)
+--- Thread: how load helper in a model? (/thread-74845.html)



how load helper in a model? - aparedesv - 11-14-2019

Hi,

I need load a custom helper in a Model...

It's possible?

I need translate $validationsRules label

Some idea?

I think to load custom helper for get user lang and set label each validationRule

thanks

the idea is something like:

helper('admin_auth'); // method comprovacio_idioma_usuari()
$idioma = comprovacio_idioma_usuari();
protected $validationRules    = [
   'nom' => ['label' => lang('Admin.nom', [], $idioma), 'rules' => 'min_length[2]|max_length[100]|required']
];


RE: how load helper in a model? - InsiteFX - 11-14-2019

You can always just add a require_once in the top of your model

Helpers are nothing but stand alone methods.

Did you try loading it in your controller then using it in your model?


RE: how load helper in a model? - Hrodriguez18 - 11-15-2019

(11-14-2019, 09:57 AM)aparedesv Wrote: Hi,

I need load a custom helper in a Model...

It's possible?

I need translate $validationsRules label

Some idea?

I think to load custom helper for get user lang and set label each validationRule

thanks

the idea is something like:

helper('admin_auth'); // method comprovacio_idioma_usuari()
$idioma = comprovacio_idioma_usuari();
protected $validationRules    = [
   'nom' => ['label' => lang('Admin.nom', [], $idioma), 'rules' => 'min_length[2]|max_length[100]|required']
];




you can load help in BaseController or Config\Autoload or function __contruct using helper('herlpername') ;


RE: how load helper in a model? - kilishan - 11-15-2019

While you can totally use the Controller's $helper var, you can load a helper at anytime with helper('my_helper_name')


RE: how load helper in a model? - aparedesv - 11-18-2019

thanks!

finally, I load the helper in controller:

in model:
protected $validationRules = [
'nom' => ['rules' => 'required|min_length[2]|max_length[100]'],
'nom_anterior' => ['rules' => 'min_length[2]|max_length[100]'],
'imo' => ['rules' => 'required|exact_length[10]'],
];

in controller:
$validation = \Config\Services::validation();

$iotsModel = new IotsModel();
$rules = $iotsModel->getValidationRules();

$idioma = comprovacio_idioma_usuari();

$rules1 = [];
foreach($rules as $key => $rule)
{
$rule['label'] = lang('Admin.'.$key, [], $idioma);
array_push($rules1, $rule);
}

$validation->setRules($rules1);

surely there are more elegant ways, but it works perfectly!