1

I'm building a multilingual site using Drupal 8 and I already managed the creation of a search tool using Views and Exposed Filters. My issue is with the translation of this tool: Drupal gives me the option for the translation of most of the elements of the view, but I can't find any options to translate the placeholder used in the exposed filter.

Is there any way to translate placeholders for those filters?

1

I'll post the solution I worked out just in case someone might need it. Using the hook_form_alter() function:

function YOUR_THEME_form_alter(&$form){
  if($form['#id'] == 'your_form_id'){
    foreach ($form['#info'] as $filter_info) {
        $filter = $filter_info['value'];
        if ($form[$filter]['#type'] == 'field_type' && $filter == 'field_title') {
            $form[$filter]['#attributes']['placeholder'] = t('your_placeholder');
        }
    }
}
| improve this answer | |
0

I found a really interesting way to do this which really doesn't affect core or mess with code. Rather, play with twig files this way:

  1. Copy the input.html.twig to your theme
  2. Now edit this file and do the following:

    {% if (attributes.placeholder is defined) %}
    {% set placeholder = attributes.placeholder|render|trans %}
    <input{{ attributes.addClass("form-control")|without('placeholder') }} placeholder="{{ placeholder }}" />{{ children }}
    {% else %}
    <input{{ attributes.addClass("form-control")|without('placeholder') }} />{{ children }}
    {% endif %}
    
  3. Then, clear your cache drush cr
  4. Now, head over to your translation UI (admin/config/regional/translate) If you are fortunate, your placeholder text will now be available to translate.

Hope that helps.

| improve this answer | |
  • Thanks for answering. It seems that I'm not lucky, because the placeholder is not available in the translation page. Any other suggestion? I'm pretty sure it has to be a way to do this. – Kelvin Joysury Feb 7 '19 at 11:50
  • If you followed the steps outlined above and once you saved this file in your theme and cleared the cache, you need to render the page the place holder is on (with your theme). This should engage the translation engine in Drupal and make that placeholder available in the administration translation page. If not, likely there is something extraordinary going on. – wilco Feb 8 '19 at 14:57
  • one more thing you can do, if for whatever reason you cannot seem to solve this using PHP, you could try Javascript. There is a function called Drupal.t(). Right a behavior that targets your form element that has the placeholder in it. Then wrap the output with that function. Clear the cache. And as per usual, search the admin translate section to find your placeholder. – wilco Feb 8 '19 at 15:02

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.