gpt4 book ai didi

drupal - 在 drupal8 中的 Twig 模板中渲染表单

转载 作者:行者123 更新时间:2023-12-02 06:32:40 24 4
gpt4 key购买 nike

我目前正在使用 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) {
}
}

现在我需要在 Twig 模板中渲染上面的变量,如下所示

 //themes/page.html.twig

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

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

最佳答案

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

模块名称/form.module

function form_theme() {

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

return $themes;
}

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

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

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

希望对你有帮助!

关于drupal - 在 drupal8 中的 Twig 模板中渲染表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708245/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com