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

时间:2016-08-09 10:23:05

标签: php forms drupal-theming drupal-8

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

我的内容类型是通过管理界面创建的,非常简单,我想要显示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>  

接口是否有办法制作它? (我想不是)

目前我已经通过

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

我的目标是修改孩子并将其更改为

<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}上显示简单自定义表单的方法吗?

编辑 - 解决方案

我直接挂了表单并更改了#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 ,因此在钩子名称中提及,模板将仅应用于该主题。

因为如果没有消息来源,您永远不会做任何事情: Create your own module with custom form

(因为钩子名称在此来源中有名称错字)

1 个答案:

答案 0 :(得分:1)

您需要使用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的::主题() - &GT; getActiveTheme();

并进行所需的更改。

希望我有所帮助,如果需要,请提出进一步的问题。

相关问题