Possible to set a new value for the field from within a custom validator?
Possible to set a new value for the field from within a custom validator?
Consider the following validator, which works...
->validator( function ( $val, $data, $field, $host ) {
// Get the item number and unit-of-measure from the submitted data
$itemNumber = $data['item_key'];
$unitOfMeasure = $data['unit_of_measure'];
// Retrieve the increment_qty from the database
$increment_qty = $db->sql("SELECT increment_qty FROM prices WHERE item_key = '{$itemNumber}' AND unit_key = '{$unitOfMeasure}'")
->fetch();
// Check if the entered quantity is a multiple of the increment_qty
if ($val % $increment_qty['increment_qty'] !== 0) {
// Compute the nearest rounded value that is higher than the input value, in appropriate increment quantities
$roundedValue = ceil($val / $increment_qty['increment_qty']) * $increment_qty['increment_qty'];
return "The quantity must be a multiple of {$increment_qty['increment_qty']}.";
}
return true;
})
Is it possible for me to also set a new value for the field at the same time, or can I only return the validator message?
Answers
You can -
$field->setValue('myNewValue');
should do it. However, personally I would suggest that validation should only do validation, also you can't set a valid value and return an error message at the same time - is that what you want to do (i.e. correct the user's input and then have them confirm that)?If that is what you want, have the validator return the error message and then on the client-side in a
postSubmit
event listener, look for that error message in the return and use the client-sidefield().val()
method to set the value.Allan