4

I have form alter for the user_register_form which is called. In this hook, I try to set a default value for a textfield but it doesn't work. I've tried all the syntax possible #default_value, #value, value, default_value, event in the attributes array.

This is my code.

function pre_registration_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_code_postal']['#cache']['max-age'] = 0;
  $form['field_code_postal']['#default_value'] = 'COUCOU';
  $form['field_code_postal']['#value'] = 'COUCOU';
  $form['field_code_postal']['value'] = 'COUCOU';
  $form['field_code_postal']['value']['#value'] = 'COUCOU';
  $form['field_code_postal']['value']['#default_value'] = 'COUCOU';
  $form['field_code_postal']['value']['value'] = 'COUCOU';
  $form['field_code_postal']['value']['default_value'] = 'COUCOU';
  $form['field_code_postal']['default_value'] = 'COUCOU';

  $form['field_code_postal']['#attributes']['value'] = 'COUCOU1';
  $form['field_code_postal']['#attributes']['#value'] = 'COUCOU2';
  $form['field_code_postal']['#attributes']['default_value'] = 'COUCOU3';
  $form['field_code_postal']['#attributes']['#default_value'] = 'COUCOU4';
}

How can I set a default value?

  • $form['field_code_postal'][LANGUAGE_NONE][0]['value']['#default_value'] – m1r1k May 27 '16 at 11:25
  • Thanks for your answer. It doesn't work, FYI I'm using D8 not D7. – Greg__ May 27 '16 at 11:56
4

According to this Documentation you can do something like

 $form['field_code_postal']['widget'][0]['value']['#default_value'] ='COUCOU1';

and for another guys help if you want to fill entity referenced field( also files are entity in drupal 8) use

 $form['field_image']['widget'][0]['target_id']['#default_value']= $file; // 
2

For my case I wanted a default automatic node title for my custom content type and this is how i achieved it: After knowing the ID of the node_form I wanted to alter below hook_form_FORM_ID_alter(), I output the content that make up the title field by kint($form['title']); after this I was able to determine the array structure for the form title field and achieved it by the below code: $form['title']['widget'][0]['value']['#default_value'] = 'my custom node title'; (Drupal 8.4x)

0

In my case the below code worked perfectly in Drupal 8:

$form['field_idea_department']['widget'][0]['value']['#default_value'] = "default values";
-1

In Drupal 8:

$form['field_name']['widget']['#default_value'][0] = 'value';

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.