I have a form that accepts a custom argument sourceid

 public function buildForm(array $form, FormStateInterface $form_state, $sourceid = NULL)

Now, this form is displayed in a twig template multiple times using a for loop. For each instance of this form the sourceid is different in the twig template. The value of the sourceid is present in the twig template. Can I pass it to the form from the twig template itself? Or should I modify my controller and render the form in the template along with the id?

Code in the twig template displaying the form is as follows:

{% for item in field %}
    {% if item.content %}
      <p> {{ item.content|raw }} </p>
      <p> {{ item.sourceid|raw }} </p>
      <div>{{ metadata_form }}</div>
    {% endif %}
(% endfor %}

The variable metadata_form has the form element in it.

  • 1
    Drupal forms are built in PHP, core uses a form controller, and then rendered via twig templates. When you are trying this you probably run in another problem, so I link it here drupal.stackexchange.com/questions/223269/…
    – 4uk4
    Commented Feb 22, 2020 at 8:45

1 Answer 1


I think the most elegant way is to modify your controller so all the logic happens in the controller and only the markup in twig. If you have that option that's the way to go.

That being said, there are ways to get what you want. The most convenient way I know is the twig_tweak module and use the function

{{ drupal_form('yourmodule\\namespace\\Form\\yourForm', sourceid) }}

I have not tested it myself but it should work.

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.