Saturday, November 11, 2017

Theme the node edit form of the custom content type in Drupal 8

Theme the node edit form of the custom content type in Drupal 8

/**
* Implements hook_theme_suggestions_alter().
*/
function MyModuleName_theme_suggestions_alter(array &$suggestions, array $variables, $hook) {
  if ($hook == 'node_edit_form') {
    if ($node = \Drupal::routeMatch()->getParameter('node')) {
      $content_type = $node->bundle();
    } else {
      $current_path = \Drupal::service('path.current')->getPath();
      $path_args = explode('/', $current_path);
      $content_type = $path_args[3];
    }
    $suggestions[] = 'node_edit_form__' . $content_type; // Note: You can also specify a custom theme ID here. See hook_theme() below.
  }
}

The following code (hook_theme) is optional:

/**
 * Implements  hook_theme($existing, $type, $theme, $path)
 */
function mydemo_theme() {
  return [
    'my_custom_theme_id' => [
      'render element' => 'form',
      #'path' => '/var/www/html/drupal8/web/modules/custom/mydemo/templates',
      'template' => 'asdf222',
    ],
  ];
}

Next, create twig templates in your theme's template directory in the form of node-edit-form--NODE-TYPE-SEPARATED-WITH-DASHES.html.twig:


<b>Test</b>

{{ form.form_id }}
{{ form.form_token }}

{{ form }}

Reference:

https://www.drupal.org/forum/support/post-installation/2015-10-31/drupal-8-node-edit-template

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Render%21theme.api.php/function/hook_theme_suggestions_HOOK_alter/8.2.x

https://drupal.stackexchange.com/questions/200602/override-theme-template-from-module-without-implementing-a-theme

No comments: