Drupal 8 自定义模板内容类型表单页面

Drupal 8 Customize template content type form page

我正在尝试自定义一个简单的添加表单页面。

我的内容类型是通过管理界面创建的,非常简单,它有 4 个我要显示的字段。

但我想在未来显示更多字段。以及系统管理的最大值。

我需要在我的表单中显示第 1 部分和第 2 部分。第 1 部分是 "my account information",它有登录名和密码字段。第 2 部分是 "my details",它有 phone 个号码、地址字段。

我的页面:

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>  

界面有办法实现吗? (我觉得不是)

现在我通过

创建了一个新的$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>

我的目标是修改children,改成

<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',并且当然没找到

我想要一些简单的东西,你可以快速理解和修改,但它是 hooking world!!我不想为此创建一个模块...

也许我走得太远(或不够),有人建议找到一种在 /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[=62 中添加了一个名为 custom-node-inscription-form.html.twig 的模板=]文件夹

我的主题名称是 fiters,因此如挂钩名称中所述,模板将仅应用于该主题。

因为你永远不会在没有来源的情况下做任何事情:Create your own module with custom form

(注意这个源中的钩子名称有错别字)

你需要使用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();

并进行所需的更改。

希望对您有所帮助,如有需要请提出更多问题。