Using moodleforms and renderers together

Using moodleforms and renderers together

ved Michael Gwynne -
Antal besvarelser: 1

This is more a question of best practice.

I am creating a page and a renderer (that extends plugin_renderer_base). I need to have a form on the page that will submit data back to the same page. My question is, should I can the form inside my render_ method and if so, where should I do all the logic such as $form->get_data() and $form->set_data()? It doesn't seem right to do it inside the renderer, but if I do it anywhere outside, I will have to call the form constructor again which also doesn't seem right.

Or, does anyone know of a good example in the Moodle source code.

Thanks,

Gennemsnitsbedømmelse: -
I svar til Michael Gwynne

Re: Using moodleforms and renderers together

ved Davo Smith -
Billede af Core developers Billede af Particularly helpful Moodlers Billede af Peer reviewers Billede af Plugin developers

Logic such as $form->get_data() certainly doesn't belong inside a render - it is part of the functionality of the page, rather than the output for the page.

A good approach, in my opinion, would be to create a class to hold the data for your page, that implements 'renderable'. You can then pass into this class a reference to the $form instance you have already created and checked with get_data().

e.g. (very roughly)

$form = new my_page_form();
...
if ($form->get_data()) {
...
redirect(...);
}
...
$pagedata = new my_renderable_page_data_class();
$pagedata->set_form($form);
// Pass any further data needed to draw the page into this class as well
...
echo $myrendererinstance->render($pagedata); // Somewhere inside this a function render_my_renderable_page_data_class(my_renderable_page_data_class $data) can output the page, including the form reference stored inside it

I'm more than happy to be corrected on this, but that would be the way I'd approach it.

Gennemsnitsbedømmelse:Useful (1)