[Form API] set_data() and definition_after_data()

[Form API] set_data() and definition_after_data()

by Camilo Rivera -
Number of replies: 3
Hi,

Is it possible that set_data() could be overriding some values set during definition_after_data()?

That's what it seems to be happening on a quiet complex form I'm working on. I run some test on simpler forms and I couldn't recreate the problem so it seems I'm doing something wrong.

I was wondering if someone else ever faced a similar problem.

Thanks.
Average of ratings: -
In reply to Camilo Rivera

Re: [Form API] set_data() and definition_after_data()

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

First, be aware that definition_after_data is a nasty hack. Sometime it is the only option, but if you can possibly make you form without using it, then you should.

As the name suggests, definition_after_data is run after set_data, so set_data cannot override what it does. However, for any field where data is passed in through set_data, that value is used rather than the default value of a field. Therefore, if you call setDefault in definition_after_data, then the value passed to set_data will take precedence over that.

Average of ratings: Useful (1)
In reply to Tim Hunt

Re: [Form API] set_data() and definition_after_data()

by Camilo Rivera -
I didn't know that definition_after_data() should be avoided. I'm using it to alter some element values after the user has selected certain options.

Should I be doing it inside the form definition instead?
In reply to Camilo Rivera

Re: [Form API] set_data() and definition_after_data()

by Camilo Rivera -

I was executing get_data() before set_data(), that was causing definition_after_data() to be executed too early.

if( !$data = $mform->get_data() ) {
    $mform->set_data( $defaults );
    $mform->display;
}

Just moved set_data() outside the block:

$mform->set_data( $defaults );
if( !$data = $mform->get_data() ) {
    $mform->display;
}