I am trying to customize a simple add form page.
My content type, created via admin interface, is very simple, it's got 4 fields I want to display.
But I want, in the future, to show more fields. And the maximum to be managed by the system.
I need to display in my form part 1 and part 2. Part 1 is "my account information", it has login and password fields. Part 2 is "my details", it has phone number, address fields.
My page :
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>
Is there a way by the interface to make it ? (I think not)
For now I have created a new $suggestions via
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']);
}
}
I can create 'form--node-inscription-form.html.twig', in it I have
<form{{ attributes }}>
{{ children }}
</form>
My goal would be to modify children and change it to
<form{{ attributes }}>
<h1>my account</h1>
{{ form.login }}
{{ form.password}}
<h1>my details</h1>
{{ form.address }}
{{ form.phone }}
</form>
But it is not working, but ! (again) I found that you could add a file named 'node-inscription-form.html.twig' and modify at your will... it crashed and asked for '.html.twig', and of course didn't find it.
I wanted something simple, that you could understand and modify quickly but it is hooking world !! I didn't want to create a module just for that...
Maybe I went too far (or not enough), anyone has a suggestion to find a way to display an easy custom form on /node/add/{content} ?
Edit - the solution
I hooked directly the form and changed the #theme, which is looking for a new template file with the same name.
I deleted fiters_theme_suggestions_alter function and added
/**
* 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;
}
I added a template with the name custom-node-inscription-form.html.twig in my themes/fiters/template/form folder
The name of my theme is fiters, so as mention in hook names, the template will be applied only on that theme.
Because you never do anything without sources : Create your own module with custom form
(becareful a hook name has a typo in name in this source)