How to hook_theme in drupal 8 as I did in drupal 7
Tue, 2018-03-27 22:51
In drupal 7, i used hook_theme to render form elements in a table. I set #theme key in my form on a fieldset that is a parent container to many form fields. My hook theme looked like this:
And the nutrients_form.theme.inc file looks like this:
<?php
/</strong>
* Theme function for nutrients form.
*/
function theme_nutrients_form($vars) {
$form = $vars['form'];
$header = array();
$rows = array();
foreach (element_children($form) as $key) {
$class = isset($form[$key]['#attributes']['indent']) ? 'indent' : 'no-indent';
$required = !empty($form[$key]['#required']) ? ' <span class="form-required" title="This field is required.">*</span>' : '';
$label = $form[$key]['#title'] . $required;
$row = array();
$row['data'][] = array('data' => $label, 'class' => $class);
$row['data'][] = drupal_render($form[$key]);
$rows[] = $row;
}
return theme('table', array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => 'nutrients-table'),
));
}
/</strong>
* Theme function for nutrients form.
*/
function theme_nutrients_form($vars) {
$form = $vars['form'];
$header = array();
$rows = array();
foreach (element_children($form) as $key) {
$class = isset($form[$key]['#attributes']['indent']) ? 'indent' : 'no-indent';
$required = !empty($form[$key]['#required']) ? ' <span class="form-required" title="This field is required.">*</span>' : '';
$label = $form[$key]['#title'] . $required;
$row = array();
$row['data'][] = array('data' => $label, 'class' => $class);
$row['data'][] = drupal_render($form[$key]);
$rows[] = $row;
}
return theme('table', array(
'header' => $header,
'rows' => $rows,
'attributes' => array('id' => 'nutrients-table'),
));
}
I get errors related to missing twig file when attempting to use the same code in Drupal 8 and I'm a bit lost how to accomplish the same thing.