1

When I add a button inside the '#rows' key of a table element, the submit function is not called.

class MyForm extends FormBase
{

   public function buildForm(array $form, FormStateInterface $form_state)
    {
        $my_button = [
            '#type' => 'submit',
            '#value' => $this->t("Click"),
            '#submit' => [
                '::custom_submitForm'
            ]
        ];
        $form['my_table'] = [
           // '#tree' => TRUE,
            '#theme' => 'table',
            '#header' => [
                'Column 1','Column 2'
            ],
            '#rows' => [
                [$this->t("Blabla"), ['data'=>$my_button]]
            ],
        ];
        return $form;
    }
    // other stuff

What is the best workaround for this?

EDIT TO ADD:

As a first try to understand what is going out, I have allowed the children function to consider '#rows' as children (see Drupal\Core\Render\Element::children)

  public static function children(array &$elements, $sort = FALSE) {
     ...
    foreach ($elements as $key => $value) {
      if (is_int($key) || $key === '' || ($key[0] !== '#' || $key=='#rows')) {
     ...

This is solving the issue (the handler is called), but of course, this change generate many other problems.. But now, we can understand why the submit handler was not called.

I have added an issue in the drupal queue: https://www.drupal.org/project/drupal/issues/3166899

I am not asking to correct this bug, but what would be the best workaround.

8
  • if you do $form['my_button'] = [ ... it get called? <-- it should, move into an empty row with CSS.
    – No Sssweat
    Aug 24, 2020 at 10:08
  • 1
    yes it works... Your solution is to create a table inside buildForm() by adding the raw html code in the "#prefix"=>'<td>'/'#suffix'=></td> of each table element? This is what I was yhinking too... but waiting other ideas
    – Baud
    Aug 24, 2020 at 10:15
  • It wasn't, but that sounds more clever.
    – No Sssweat
    Aug 24, 2020 at 10:22
  • ;-) thank you...
    – Baud
    Aug 24, 2020 at 10:36
  • 2
    Use '#type' => 'table' and don't use #rows. See drupal.stackexchange.com/questions/185032/…
    – 4uk4
    Aug 24, 2020 at 11:21

1 Answer 1

2

Use instead of #theme a form element #type:

'#type' => 'table'

The table form element has an extra step for processing when used in a form.

You don't need '#rows'. Any array key not starting with #, also the index added automatically by appending a row with [], is considered to be a renderable child and displayed as row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.