3

How can I change the search form placeholder value? I can change the value of it in my .theme file, but I want it to be also translatable.

What is the correct way of doing this?

screenshot

10

You don't alter a TranslatableMarkup object: You replace it with another TranslatableMarkup object you obtain from t('The new placeholder') or new TranslatableMarkup('The new placeholder') (or a method returning a TranslatableMarkup object).

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['title'] = t('The new placeholder');
}

The result of this code is the following (on Google Chrome running on OS X El Capitan).

screenshot

What you are showing is not the placeholder, but the input title. To change the placeholder of a form element, you should use code similar to the following one.

function mytheme_form_search_block_form_alter(&$form, FormStateInterface $form_state) {
  $form['keys']['#attributes']['placeholder'] = t('The new placeholder');
}

Using this code, you get the following result.

screenshot

-1

This worked for me:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if ($form_id == 'search_form') {

    $form['basic']['keys']['#title'] = 'Your Title'; 
  }
}
  • 3
    Welcome to Drupal answers! For benefit of future readers, it is always recommended to add some explanation to your answer. Code-only answers are not always self-explanatory. – AjitS Jan 8 '18 at 7:14
0

Its working for me

<?php

use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_form_alter().
 */
function MODULE_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
 if ($form_id == 'search_block_form') {
   $form['keys']['#title'] = t('Your custom Title');
 }
}
1

I think, we could alter the form details from hook_form_FORM_ID_alter, The following code would help to fix the issue :)

function my_module_form_search_block_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['keys']['#title'] = t('Your custom Title');
  $form['keys']['#attributes']['title'] = t('Your custom Placeholder');
}

The above code will change the title and placeholder for the search form.

0

you can use form alter for this

 function yourtheme_form_search_block_form_alter(&$form, &$form_state) {
      $form['keys']['#attributes']['placeholder'][] = t('enter the terms you wish to search for');
    }
  • @ Naveen Thanks for your contribution, In our case its not taking placeholder attributes, its working when I change $form['keys']['title'] = t('new place holder'). – Karthikeyan Manivasagam Aug 18 '17 at 12:04

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.