ketter
ketter

Reputation: 21

Using Language from Model in Module of CodeIgniter 4.1 for form validation messages

I need integrate diferent languages for my form validation messages. I using form validation in my Model class and a file in my Language directory inside my Module. I'm working in HMVC pattern. Here some of my code:

In my ShopsModel file:

 protected $validationRules = [
   "name" => "required|min_length[4]|max_length[80]",
   "legalName" => "required|min_length[4]|max_length[80]|is_unique[shops.legalName]"
 ]; 

 protected $validationMessages = [
      "name" => [
      "required" => "Nombre es requerido",
        //"required" =>  lang('Shops.nameRequired'),  --My Test for load messages from Languague File
      "min_length" => "Minimum length of name should be 4 chars",
      "max_length" => "Maximum length of name should be 80 chars"
        ],
    "legalName" => [
      "required" => "legalName is required",
      "is_unique" => "Ya existe otro registro con el mismo nombre",
      "min_length" => "Minimum length of name should be 4 chars",
      "max_length" => "Maximum length of name should be 80 chars"
        ]
];

In my Languague File:

return [

    'name'          => 'Nombre:',
    'phName'        => 'Nombre corto',
    'nameRequired'  => 'Nombre es requerido',
    'phLegalName'   => 'Nombre registrado',
    
];

If I uncomment the line commented in my ShopsModel file I get This error:

Fatal error: Constant expression contains invalid operations

There are another way for implement this? Whatever help is wellcome

Thanks

Upvotes: 0

Views: 311

Answers (1)

Canh
Canh

Reputation: 584

The problem was explained in this post. You can solve your problem just by move your $validationRules to the function that handles the validation:

function validateMessages(){
  $validationMessages = [
      "name" => [
      "required" => "Nombre es requerido",
      "required" =>  lang('Shops.nameRequired'),
      "min_length" => "Minimum length of name should be 4 chars",
      "max_length" => "Maximum length of name should be 80 chars"
        ],
    "legalName" => [
      "required" => "legalName is required",
      "is_unique" => "Ya existe otro registro con el mismo nombre",
      "min_length" => "Minimum length of name should be 4 chars",
      "max_length" => "Maximum length of name should be 80 chars"
        ]
  ];
  // other code is here
}

Upvotes: 0

Related Questions