Validate data when required in cakePHP 3

1

I have been with this situation for a week and I can not find information on the subject, the following happens, I have a form that has controls that are shown when required, for example, my application registers a match between two players and depending on the mode of the game will appear some controls and others not, the case is that I need to validate those fields when the modality requires it, a more detailed example, a game of billiards is going to be recorded, the modality requires registering the tacadas and the points of each player, here in this case I need to validate those fields, if the modality is 8 ball billiards it is not necessary to register tacadas and points, so I do not want to be validated, in my Model I have the following:

public function validationDefaul(Validator $validator) {
  //Otras reglas

    $validator      
        ->add('tacadas',['requireTacadas' => ['rule' => 'requireTacada','provider' => 'table', 'message' => 'Requerido.']])     
        ->add('tacadas','valid',['rule' => 'numeric', 'message' => 'Debe ser un valor numérico.'])
        ->allowEmpty(true);      

  return $validator;
}

The requireTacadas function is as follows:

function requireTacadas($value,$context) {

    if($context["data"]["modal_cushion_point"] && empty($context["data"]["tacadas"])) {
        return false;
    } else { 
        return true; 
    }

When the modality requires registering the tacadas and the user leaves it blank, it shows me the text "This field can not be left empty" instead of the "Required", if the modality does not need to record the tacadas as the 8-ball pool and the controls are not visible does not allow me to save the game because it continues to validate it as empty, in my template I tried to put the required controls to false and still validates them as empty and that is mandatory, it should be noted that in the BD fields allow null data.

Use CakePHP 3.5

    
asked by Enecumene 03.02.2018 в 21:59
source

1 answer

1

I have found the solution to my problem, and that is that we have to use the event beforeValidate (), in the model we put the validation rule in this way

public function validationDefault(Validator $validator) {

    $validator
    ->add('tacadas','valid',['rule' => 'numeric', 'message' => 'Debe ser un valor numérico.'])
    ->notEmpty('tacadas','Requerido');

    return $validator;

}

EYE remove the use of requirePresence because it automatically validates all the time as a required field, in the beforeValidate event we do the following:

public function beforeValidate(){
    if(!$this->data["Partidos"]["modal_cushion_point"]) {
        unset($this->data["Partidos"]["tacadas"]);

        return true;
    } else {
        return false; //es requerido
    }
}

And ready, we can fields when required.

Greetings.

    
answered by 03.02.2018 в 23:10