I have in Drupal 10 made a simple table that is being build with a PHP as part of a module.
When I use a buildForm-function, I can not position the input fields. I want these to be as if they were generated in the table column. That would be easy if all was pure in the PHP module directly. But how is that done with Drupal Forms when the fields are in a buildForm.
I tried with CSS positioning (absolute ) but this is not really good enough, because of the dynamic behavior of the table.
PHP CODE:
foreach ($questions as $question) {
$sq_arr = explode(';',$question);
$result_s .= '<tr>';
$result_s .= '<td>' . $sq_arr[1] . ' : ' . $sq_arr[0] .'</td>';
$result_s .= ' <td>'.$sq_arr[4].'</td>';
$result_s .= ' <td> HERE THE INPUT ELEMENT </td>';
$result_s .= ' <td>'.$sq_arr[5].'</td>';
$result_s .= '</tr>';
}
buildForm Code:
public function buildForm(array $form, FormStateInterface $form_state) {
$form['userinput_0'] = [
'#type' => 'textfield',
'#title' => '',
'#placeholder' => 'Enter Answer 1',
'#attributes' => array(
'id' => 'userinput_0',
'autofocus' => 'autofocus',
) ] etc...
Visualisation:
I also found a another way of working, by building the table in the buildForm. But how do you pass an array (here $allData) to your buildForm from the module function?
public function buildForm(array $form, FormStateInterface $form_state) {
// This data should come from a function I have.
$allData = [
['tense+verb' => 'Indicatif Présent' , 'person' => 'nous' , 'your_answer' => '', 'correct_answer' => 'retournons'],
['tense+verb' => 'Indicatif Passé Composé', 'person' => 'nous' ,' your_answer' => '', 'correct_answer' => 'avons isolé'],
['tense+verb' => 'Indicatif Passé Composé', 'person' => 'elles' , 'your_answer' => '', 'correct_answer' => 'ont pesé'],
['tense+verb' => 'Indicatif Passé Composé', 'person' => 'elles' , 'your_answer' => '', 'correct_answer' => 'ont pesé'],
['tense+verb' => 'Indicatif Passé Composé', 'person' => 'elles' , 'your_answer' => '', 'correct_answer' => 'ont pesé'],
];
$form['my_table'] = [
'#type' => 'table',
'#header' => ['Tense+Verb','Person','Your Answer','Correct Answer'],
'#prefix' => '<div class="table table-hover table-mc-light-blue">',
'#suffix' => '</div>',
];
foreach ($allData as $index => $row) {
$form['my_table'][$index]['tense+verb'] = [
'#markup' => $row['tense+verb'],
];
$form['my_table'][$index]['person'] = [
'#markup' => $row['person'],
];
$form['my_table'][$index]['your answer'] = [
'#type' => 'textfield',
'#title' => '',
'#size' => 30,
'#attributes' => array(
//'style' => 'height: 20px;',
'placeholder' => 'Your answer',
'id' => 'userinput_0',
'autofocus' => 'autofocus',
),
];
$form['my_table'][$index]['correct answer'] = [
'#markup' => $row['correct_answer'],
];
}