0

I have this form tempate

<div class="a">
    {{ form.card.a }}
</div>
<div class="a">
    {{ form.card.b }}
</div>

and I want to to frame it with tag like this.

<a href="/card?id={{ form.card.card_link }}"> 
    <div class="a">
        {{ form.card.a }}
    </div>
    <div class="a">
        {{ form.card.b }}
    </div>
</a>

so I made

$form['card']['card_link'] = [
  '#type' => 'item',
  '#markup' => $this->getCardLink(), //returns integer
];

But it still doesn't show what it supposed to. It inserts <div id="edit-card-link" class="some stuff">needed integer</div> inside href="<here>"

How should I fix this?

0

The item element type is a form element, Drupal\Core\Render\Element\Item.

This means that it gets a form element wrapper by default.

Rather than rendering the <a> wrapper in the Twig template, you could include it in the render array, and add form.card.a and form.card.b as its children:

// In your form handler class

function buildForm($form, $form_state) {
  // ...

  $form['card_link'] = [
    '#type' => 'html_tag',
    '#tag' => 'a',
    '#attributes' => [
      'href' => '/card?id=' . $this->getCardLink()
    ],
  ];

  $form['card_link']['a'] = array_merge($form['card']['a'], [
    '#prefix' => '<div class="a">',
    '#suffix' => '</div>',
  ]);

  $form['card_link']['a'] = array_merge($form['card']['b'], [
    '#prefix' => '<div class="a">',
    '#suffix' => '</div>',
  ]);

  // ...
}

The template then simplifies to this:

{{ form.card_link }}
  • it passed the value but pops error then User error: "card_link" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core\lib\Drupal\Core\Render\Element.php). – Den Aug 16 at 14:09
  • Sorry about that. I forgot that the renderer won't accept plain values as elements. I've rewritten the answer to build a render array which replaces the markup in the Twig template. – Brad Treloar Aug 16 at 20:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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