3
votes

Im curently using drupal 8 and I have created form using form api,

The below code under Module directory

  // module/src/Form/ContributeForm

  class ContributeForm extends FormBase {

  public function getFormId() {
     return 'amazing_forms_contribute_form';
  }

  public function buildForm(array $form, FormStateInterface $form_state) 
  {
      $form['title'] = array(
           '#type' => 'textfield',
           '#title' => t('Title'),
           '#required' => TRUE,
      );
      $form['video'] = array(
           '#type' => 'textfield',
           '#title' => t('Youtube video'),
      );
      $form['video'] = array(
          '#type' => 'textfield',
          '#title' => t('Youtube video'),
      );
     $form['develop'] = array(
          '#type' => 'checkbox',
          '#title' => t('I would like to be involved in developing this 
           material'),
    );
    $form['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Submit'),
);
return $form;
}

public function validateForm(array &$form, FormStateInterface $form_state) {
}

public function submitForm(array &$form, FormStateInterface $form_state) {
}
}

Now I need to render above vairables in twig template like below

 //themes/page.html.twig

 <body>
    {{form.title}}
    {{form.video}}
    {{form.video}}
 </body>

the twig will be under theme folder.Is it possible to get variable in page.html.twig file??

2

2 Answers

5
votes

The best way to render and custom your form via Twig, you'd use $form['#theme'] value in your form. Example below:

module_name/scr/Form/your_form.php

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

       $form['#theme'] = 'your_form_theme';

       return $form;
}

module_name/form.module

function form_theme() {

    $themes['your_form_theme'] = ['render element' => 'form'];

    return $themes;
}

What is left is creating your custom twig and insert you form fields.

module_name/templates/your-form-theme.html.twig

<body>
    {{form.field_1}}
    {{form.field_2}}
    {{form.field_3}}
 </body>

Hope it helps you!

1
votes

You can create a page by using the controller. From that, you can get the form elements.

Create a module_nameController.php file inside src/Controller folder. In that file create a class that should be extended to Controllerbase. In that file, by using form builder function you can get the form elements.