1

I have a template in which I've manually built a form. It renders some variables that come from a controller.

I've looked over the Form API and I think I should build the form using that. But I'm not quite sure how to go about it.

I'm relatively new to Drupal 8 and to be perfectly honest the Documentation is good, if one knows what to look for. It's not the case here.

Basically what I'm asking, is it possible(or rather advised) to somehow grab the form in the controller, and instead of passing the variables to the template, simply pass the created form to the template?

I'm assuming it would be better to do that, although I'm note quite sure that's the case.

2 Answers 2

2

This is definitely possible (and preferable). There are a few ways to do this, but I think the preferred approach is to first specify your form in your routing entry (mymodule.routing.yml)

mymodule.some.route:
  path: '/foo/bar'
  defaults:
    _form: '\Drupal\mymodule\Form\MyForm'
    _title: 'My form title'

The routing system will automatically build your form for you. The class \Drupal\mymodule\Form\MyForm should implement FormInterface. An easy starting point is to extend \Drupal\Core\Form\FormBase.

There are several examples of this in core. For instance, the entity.user.admin and user.admin_permissions routes in users.routing.yml.

0

Too late but incase someone stumbles across this:-

Here is a simple guide on how to create a form in drupal 8 https://www.valuebound.com/resources/blog/step-by-step-method-to-create-a-custom-form-in-drupal-8

And if you want to embed a form in controller check this out:- How do I embed a form in a controller response?

To theme your form. You need to implement hook_theme() in your .module file to define a new theme implementation. Something like this:-

public function buildForm(array $form, FormStateInterface $form_state) {

       //Your code
       $form['#theme'] = 'a_b_c';

       return $form;
}

And then in your .module file attach

function example_theme() {
  return [
    'a_b_c' => [
      'render element' => 'form', // here 'form' is a variable name and can be anything you want.
    ],
  ];
}

And then you can print your variables in templates/a_b_c.html.twig something like:

{{ form.name }} //if name is your form element.

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.