我正在尝试自定义一个简单的添加表单页面。
我的内容类型是通过管理界面创建的,非常简单,它有 4 个我想显示的字段。
但我想在未来展示更多领域。以及系统能够管理的最大数量。
我需要在我的表单中显示第 1 部分和第 2 部分。第 1 部分是“我的帐户信息”,它有登录名和密码字段。第 2 部分是“我的详细信息”,它有电话号码、地址字段。
我的页面:
My title
<form>
<h1>my account</h1>
<field>login</field>
<field>password</field>
<h1>my details</h1>
<field>phone_number</field>
<field>address</field>
<button>add</submit>
</form>
有没有办法通过接口(interface)来实现它? (我认为不是)
现在我已经通过创建了一个新的$suggestions
function fiters_theme_suggestions_alter(array &$suggestions, array $variables)
{
if (
isset($variables['element'])
&& isset($variables['element']['#type'])
&& $variables['element']['#type'] == 'form'
&& \Drupal::service('path.current')->getPath() == '/node/add/inscription'
){
$original_theme_hook = $variables['theme_hook_original'];
$suggestions[] = $original_theme_hook . '__' . str_replace('-', '_', $variables['element']['#id']);
}
}
我可以创建'form--node-inscription-form.html.twig',其中我有
<form{{ attributes }}>
{{ children }}
</form>
我的目标是修改 child 并将其更改为
<form{{ attributes }}>
<h1>my account</h1>
{{ form.login }}
{{ form.password}}
<h1>my details</h1>
{{ form.address }}
{{ form.phone }}
</form>
但是它不起作用,但是! (再次)我发现您可以添加一个名为 'node-inscription-form.html.twig' 的文件并根据您的意愿进行修改...它崩溃并要求提供'.html.twig',当然没找到。
我想要一些简单的东西,你可以快速理解和修改,但它是令人着迷的世界!我不想为此创建一个模块......
也许我走得太远了(或者还不够),有人建议找到一种在/node/add/{content} 上显示简单自定义表单的方法吗?
编辑 - 解决方案
我直接hook了表单并更改了#theme,它正在寻找同名的新模板文件。
我删除了fiters_theme_suggestions_alter功能并添加了
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function fiters_form_node_inscription_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
$form['#theme'] = ['custom_node_inscription_form'];
}
/**
* Implements hook_theme()
*/
function fiters_theme() {
$themes['custom_node_inscription_form'] = [
'render element' => 'form'
];
return $themes;
}
我在我的themes/fiters/template/form文件夹中添加了一个名为custom-node-inscription-form.html.twig的模板
我的主题名称是fiters,因此正如 Hook 名称中提到的那样,模板将仅应用于该主题。
因为你从不做没有来源的事情: Create your own module with custom form
(请注意,此源中的钩子(Hook)名称有一个拼写错误)
最佳答案
您需要使用hook_form_FORM_ID_alter https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21form.api.php/function/hook_form_FORM_ID_alter/8.2.x
在更改中,您需要检查您是否处于您想要的主题: \Drupal::theme()->getActiveTheme();
并进行您想要的更改。
希望我的回答对您有所帮助,如果需要,请提出进一步的问题。
关于php - Drupal 8 自定义模板内容类型表单页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38848168/