Score:1

How to pass a simple variable into form for twig? Not a form element

pr flag

I have a form that is working just fine. Now I need to make some logic in its twig file based on some field value. How do I pass that variable into twig? I tried a simple solution and it works, but I get errors.

$form['dates']['arrival'] = [
  '#type' => 'date',
  '#title' => $this->t('Arrival'),
  '#required' => TRUE,
  '#default_value' => $form_state->getValue(
    ['dates', 'arrival'],
  ),
];

$form['some_value'] = $form_state->get('max_guests');

Whatever I do I get:

User error: "some_value" is an invalid render array key in Drupal\Core\Render\Element::children()....

I have seen the other answer, I defined

$form['#max_guests'] = $form_state->get('max_guests') ?? 0;

Now I can not output it in twig.

I tried

{{ element.max_guests }}

{{ max_guests }}

Nothing works, please help

4uk4 avatar
cn flag
@Jaypan, that would be two solutions at once. You only need one, either put a hash tag in front of the form key or, if you want to render the form key together with the other form elements, build a render array, for example with `#markup`. Oleh Bardiuk, the answer to the last part of your question is: `{{ element['#max_guests'] }}` or `{{ form['#max_guests'] }}`.
Jaypan avatar
de flag
Oh yes, I didn't notice the hashtag on the code I copied. Deleted my comment.
Oleh Bardiuk avatar
pr flag
Yeah, the old good PHP's `element['#max_guests']` helped, thanks. <irony>Things are very intuitive and consistent in twig</irony>
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.