Jun 4, 2014

Theme functions are gone, more or less

For the Project Listing tab of the module, the D7 version defines an item in  hook_menu()  that names function  optimizely_project_list_form()  to be called to create the form.

(1)  That function first queries the database to collect the raw data for existing projects.

(2)  Through the #theme property, the function specifies use of a theme hook that is declared in hook_theme(). The theme hook is implemented by a theme function, which builds most of the render array.

(3)  The theme function makes an explicit call to the core theme() function to do the actual rendering, passing table as the first param for that call.

Because there are indications that in Drupal 8 the use of theme functions is strongly discouraged, calling  theme() directly is discouraged, and because the D7 implementation seemed unnecessarily complex, I studied the code to see if I could come up with an alternative.

The upshot is that I was able to refactor the code to avoid what is deprecated and to make the call structure a little simpler.

Keep in mind that for implementing forms, we are now dealing with a class derived from FormBase.

(1)  The buildForm() method first accesses the database to collect raw data, exactly as before.

(2)  For the #theme property of the render array, the method provides a value of table. No theme hook is used, nor is there a call to theme().

(3)  The gut logic that was previously in the theme function was extracted into a private method of the same class that implements the form. This new method is directly called once for each project, i.e. each row of the table, to provide its addition to the render array.

One notable thing about this conversion task is that I was able to copy-paste large chunks of code as is. It was only the overall flow that was changed. The contents and the details of the resulting render array were almost exactly the same, as were almost all of the control structures.

Sources:

Completely new theme/template system: Twig
https://drupal.org/node/1831138

No comments:

Post a Comment