Welcome Guest, Not a member yet? Register   Sign In
Validation callback function in Model with several parameters
#1

Dear all,

I am trying to use a custom validation callback function, from a model (not from the controller, as I am trying to keep them slim), and this function takes two parameters.

As described in the documentation, I am using arrays to make these methods callable.

Here is a sample of my controller's method :


PHP Code:
public function saveOrUpdate()
{
   $this->load->model('TravelModel');
   if ($this->TravelModel->runValidation() == FALSE) {
       //An error occured --> REPOST form
       //...
   } else {
        //Validation OK --> SAVE values
        //...
   }



Here is a sample of the model's method :

PHP Code:
public function runValidation():bool{
 
  $this->load->library('form_validation');
 
  $this->form_validation->set_rules('title''Title''trim|required|max_length[150]');
 
  $this->form_validation->set_rules(
 
      'startdate',
 
      'Start',
 
      array(
 
          'required',
 
          array($this->TravelModel'endAfterStart['.$this->input->post('enddate').']'),
 
          array($this->TravelModel'isValidDate'),
 
      )
 
  );
 
  $this->form_validation->set_rules('enddate''End', array('required',array($this->TravelModel'isValidDate')));

 
  return($this->form_validation->run());



And finally, an example of two callback functions :

PHP Code:
public function isValidDate(string $date): bool
{
 
  if (isValidBelgianDate($date)) return true;
 
  $this->form_validation->set_message('isValidDate''Date is invalid');
 
  return false;
}

public function 
endAfterStart($startDate$endDate): bool
{
 
  $startDate DateTime::createFromFormat('!d/m/Y'$startDate);
 
  $endDate DateTime::createFromFormat('!d/m/Y'$endDate);

 
  $this->form_validation->set_message('endAfterStart''Start date should be less than end date.');
 
  return ($endDate >= $startDate);



For your info, isValidDate is working perfectly, since this function takes only one parameter.
However endAfterStart is not working. I always get these errors :

Severity: Notice
Message: Array to string conversion
Filename: libraries/Form_validation.php
Line Number: 771


Message: preg_match() expects parameter 2 to be string, array given
Filename: libraries/Form_validation.php
Line Number: 695



What can I do?

If I extend the CI_Form_validation in a MY_Form_Validation, this mechanism is working quite well (you just have to pass multiple parameters as a single string with separators) but I really would like to keep these callbacks in my models together.

Thank you very much.
Reply
#2

@b126,

Why don't you var_dump the values that are being sent into endAfterStart and see what is being passed to the method. You may just need to fix the value that is being sent to the method.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB