General developer forum

Can you set form values at the validation() step?

 
Picture of David Poly
Can you set form values at the validation() step?
 

I'm trying to set data in a hidden mod_form input from validation() but even though I can see that the value has been set if I check the input value afterward, once I get to add_instance() in lib.php the hidden input value is gone.

The reason I want to set this value from validation is that I'm doing a series of validations and requests to validate that a Youtube video ID is valid. If it is, I calculate the video's aspect ratio from the YT API response I got.

sot it looks a bit like...

function validation($data, $files) {
    ...
    if(yt) {
        $input = $mform->getElement("aspect_ratio[$i]");
        $input->setValue($aspectratio);
    }
}

Assuming everything else validates, the data passed to add_instance() has an empty value for this element. All the other data is there.

Is there a way to do this the way I'm trying to do it or do I need to replicate that logic but from definition_after_data() instead? To me it feels illogical to try and calculate this aspect ratio on any user entered data without first validating it's an actual valid Youtube video with a valid response from the Youtube API.

I guess I could also do it from add_instance but that means querying the YT API once more to get the exact same data I just pulled from the validation.

Thanks for any help Moodle community!

 
Average of ratings: -
Tim at Lone Pine Koala Sanctuary
Re: Can you set form values at the validation() step?
Core developersDocumentation writersParticularly helpful MoodlersPlugin developers

To get data out of the validation process, don't try to save it into a hidden form field. Just save it as $this->computeraspectratio (or something), and add a $this->get_computed_aspect_ratio method (or something similar). (Or, you could override get_data() to include the extra computed values.)

 
Average of ratings: -