Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

Code snippet that can be used to change a field element in form using hook_form_alter in Drupal 8.

 * @param $form
 * @param $form_state
 * @param $form_id
function mytheme_form_alter(&$form, &$form_state, &$form_id)
    if ($form_id == 'FORM_ID'){

//            to remove  description      

//            to update title 
            $form['name']['#title'] = t("Your Custom name");

//            to update placeholder
            $form['name']['#attributes']['placeholder'] = 'Custom placeholder';

//            to add class
            $form['name']['#attributes']['class'][] = 'custom_class';

//            to add class to submit button
            $form['actions']['submit']['#attributes']['class'][] = 'submit_class';

//            to change value of submit button
            $form['actions']['submit']['#attributes']['value'][] = t('Submit Value');

//            to add prefix 
            $form['actions']['submit']['#prefix'] = '<div class="class_div_prefix">';

//            to add suffix
            $form['actions']['submit']['#suffix'] = '</div>';

//           to update All option with your text
           $form['field_name']['#options']['All'] = t('Select option'); 


Submitted by Gaetano (not verified) on Fri, 08/14/2020 - 16:17 Permalink

I tried 2 lines of your code but they don't work, you have to put all the fields in the array for it to work // to update placeholder
$form['title']['#attributes']['placeholder'] = 'Custom placeholder';
      $form['title']['widget']['0']['value']['#placeholder'] = 'quello che mette sul rigo vuoto ';
// to remove description
      $form['title']['widget']['0']['value']['#description'] = 'help del campo';
am I wrong something?
Submitted by codimth on Fri, 08/14/2020 - 16:38 Permalink

here is an example to change form search:

case 'search_block_form':
    $form['keys']['#attributes']['placeholder'] = t("Search");
    $form['keys']['#attributes']['class'][] = 'form-control';


this link also can help you

Submitted by Gaetano Leoni (not verified) on Thu, 11/12/2020 - 15:54 Permalink

In form_alter I tried this code $form['field_numero_quietanza_bonifico']['#attributes']['placeholder'] = 'Quietanza'; but it doesn't work, but this does $form['field_numero_quietanza_bonifico']['widget'][0]['value']['#placeholder'] = 'Quietanza';
Add new comment

Restricted HTML

Riadh Rahmi

Senior Web Developer (Drupal & Laravel)

I am a senior web developer, I have experience in planning and developing large scale dynamic web applications especially in Drupal and Laravel.

Web Posts


Page Facebook