1

Please, help. Is it possible implement different templates for form-element.html.twig? For form 'user-form' one template, and for other forms second template.

  • I'm running the same problem. In my case all fields in 'user-form' are label_display after, to solve this, I changed them in template_preprocess_form_element by fields names. – Vagner May 1 '16 at 13:53
  • Could you give example how you use did it? – Lexs May 5 '16 at 6:39
2

As you requested, this is an example how I did using field names.

In your .theme file:

function THEME_preprocess_form_element(&$variables) {
  //This is a list of fields in contact form
  $showAfter = array('name', 'mail', 'subject[0][value]', 'message[0][value]');
  if (in_array($variables['name'], $showAfter)) {
    //If is one, I change here how to display instead using different twig file
    $variables['element']['#title_display'] = 'after';
    $variables['label_display'] = 'after';
  }
}

Now, if you want use different twig file for each field name use this...

.theme file

function THEME_theme_suggestions_form_element_alter(array &$suggestions, array $variables, $hook) {
  if (isset($variables['element']['#name'])) {
    //Name can be a string like this, 'subject[0][value]'.
    //When this happen, I just get 'subject'.
    $suggestions[] = 'form_element__' . explode("[", $variables['element']['#name'])[0];
  }
}

Then in your HTML appear something like this:

<!-- FILE NAME SUGGESTIONS:
   * form-element--subject.html.twig
   x form-element.html.twig
-->

Note:
The main problem is how you get form_id in preprocess or theme_suggestions (form_element Hook), I didn't find a way to get this information.

0

I found out another way to solve my problem. In form_alter function i added this code: $form['custom_field']['theme_wrapper'] = 'form-element-custom.html.twig'; And, its help me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.