I have contact form module enabled from core drupal 8 modules.

When I use the below code it has

   $form['field_consumer_name']['widget'][0]['#title'] = 'Individual Name';

I want that this code which I have written should override default title but it does not . I would be interested in knowing how I can override title?

 function referral_q_form_contact_message_referral_form_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state ) {
   // print_r($form['field_consumer_name']['widget'][0]['#title']);
$form['field_consumer_name']['widget'][0]['#title'] = 'Consumer Name Works';

   $form['#prefix'] = '<div class="referral-container">';

   $form['field_consumer_name']['widget'][0]['#title'] = 'Individual Name';
   $form['field_referral_date']['widget'][0]['#title'] = 'Date';

   $form['field_diagnostic_code_1']['widget'][0]['#title'] = 'Diagnostic Code';


   $form['#suffix'] = '</div>';
  • I assume 'referral_q_form_contact_message_referral_form' is the name of your module. Have you tried debugging the code above to see that it is even being hit? – Kevin Jul 25 '16 at 14:46
  • referral_q is module name – harshal Jul 25 '16 at 14:47
  • contact_message_referral_form_form is name of the form_id – harshal Jul 25 '16 at 14:47
  • back to Kevin question: besides changing the title, can you prove it to yourself that ALTER is working? Can you kint / var_dump something? – ssibal Jul 25 '16 at 15:01
  • yes i tried by doing print_r($form); and it showed me array which showed that it was being hit. – harshal Jul 25 '16 at 15:01

This is the array structure of the relevant part of the form.

enter image description here

Using `$form['field_consumer_name']['widget'][0]['value']['#title'] = 'Individual Name'; worked for me.

| improve this answer | |
  • 1
    just as a small suggestion: when you hardcode ui strings, you should always use translate function. It's a good drupal habit. – ssibal Jul 25 '16 at 15:44

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.