Drupal Answers Asked by Travis Miller on October 1, 2020
My custom module has the following form route in mymodule.routing.yml
:
library_assets.add_asset_to_slideshow_modal:
path: 'library/add-to-slideshow-modal/{library_asset_nid}'
defaults:
_form: 'Drupallibrary_assetsFormAddAssetToSlideshow'
_title: 'Add to Slideshow'
requirements:
_permission: 'access content'
And I have a link (in another form) which opens this form in a modal dialog:
$asset_display_title = $this->node->field_la_display_title->value;
$modal_form_url = Url::fromRoute('library_assets.add_asset_to_slideshow_modal', [
'library_asset_nid' => $this->node->id(),
]);
$form['actions']['add_asset_to_slideshow'] = [
'#type' => 'link',
'#title' => $this->t('Add to Slideshow'),
'#url' => $modal_form_url,
'#attributes' => [
'class' => [
'use-ajax',
'btn',
'btn-blue',
'w-100',
'd-block',
],
'data-dialog-type' => 'modal',
'data-dialog-options' => json_encode(['title' => $asset_display_title, 'width' => 600]),
],
];
All of this is working – the form modal appears when I click on the "Add to Slideshow Link"; it validates correctly; the form submit handler works properly, etc.
But I’m having problems theming the form. When I inspect the contents of the modal to see the template suggestions, I see this:
<!-- FILE NAME SUGGESTIONS:
* form--add-asset-to-slideshow--pv65ooQgrPE.html.twig
x form.html.twig
-->
The pv65ooQgrPE
part is different every time – it seems to be randomly generated (maybe a hash of some kind?).
I obviously can’t create a template file if the filename is essentially random every time.
I tried omitting the suffix, and creating a template named form--add-asset-to-slideshow.html.twig
– but that doesn’t work.
What’s going on here? Is this an intentional feature of Drupal? (If so, where is the documentation? I’ve been unable to find it.)
Most importantly, though: what’s the proper way to theme my form, in this situation?
Thanks!
Create a .module in your module folder ex : library_assets/library_assets.module
in the .module file use this HOOK to create a new form suggestion that will be dynamically equal to form--{form-id}.html.twig
<?php
/**
1. Implement {module_name}_theme_suggestions_form_alter
*/
function library_assets_theme_suggestions_form_alter(array &$suggestions, array $variables) {
//Get the form id
// ! - you must replace the '-' with '_' in the suggestion name otherwise it won't work.
$form_id = str_replace('-', '_', $variables['element']['#id']);
// adding a new suggestion to the form template
$suggestions[] = 'form__'.$form_id;
}
Answered by Marwen Amri on October 1, 2020
Get help from others!
Recent Answers
Recent Questions
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP