【问题标题】:Render form in a Twig Template in drupal8在 drupal8 的 Twig 模板中渲染表单
【发布时间】:2017-12-08 05:26:46
【问题描述】:

我目前正在使用 drupal 8,我已经使用表单 api 创建了表单,

Module目录下的以下代码

  // 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) {
}
}

现在我需要在下面的树枝模板中渲染上面的变量

 //themes/page.html.twig

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

twig 将在主题文件夹下。是否可以在 page.html.twig 文件中获取变量??

【问题讨论】:

    标签: drupal drupal-8


    【解决方案1】:

    通过 Twig 呈现和自定义表单的最佳方式是在表单中使用 $form['#theme'] 值。示例如下:

    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;
    }
    

    剩下的就是创建您的自定义树枝并插入表单字段。

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

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

    希望对你有帮助!

    【讨论】:

    • CSRF 代币呢?
    • {{ form.form_build_id }} {{ form.form_token }} {{ form.form_id }} {{ form.actions }}
    【解决方案2】:

    您可以使用控制器创建页面。从中,您可以获取表单元素。

    在 src/Controller 文件夹中创建一个 module_nameController.php 文件。在该文件中创建一个应该扩展到 Controllerbase 的类。在该文件中,通过使用表单构建器功能,您可以获得表单元素。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-22
      • 1970-01-01
      相关资源
      最近更新 更多