2

I have a Drupal 8 contact form where the form's placeholder values are the default values of the fields. Unfortunately, this site is multilingual and I don't think it's possible to translate default field values.

Is there a way I can set the fields' default values equal to the (translatable) field labels in either a module or preprocess function?

1

You can override your contact forms(both the default and the custom ones) by adding a field widget hook. Why a field widget hook and not the usual form alter hook like D7? Because overriding the default value of the field can be done only in the respective field widget and not at the form level.

Here's the sample code:

function <mymodule>_field_widget_form_alter(&$element,  \Drupal\Core\Form\FormStateInterface $form_state, $context) {
   $field_definition = $context['items']->getFieldDefinition();
   $entity = $context['items']->getEntity();
   if(($entity->getEntityTypeId() == 'contact_message') && ($entity->bundle() == '<your-custom-form-machine-name>')) {
     if($field_definition->getName() == '<your-field-machine-name>') {
       $element['value']['#default_value'] = 'Hi there!';
     }
   }
}

NOTE This has been tested with Drupal 8.1.1.

0

I managed to figure it out with a preprocess function using hook_form_id_alter. I got an array of the necessary field names, and looped through it assigning the field label value to the placeholder value. If this is bad form, let me know.

function yourtheme_form_yourformid_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $field_list = array_keys($form['#group_children']); //you might need to find a different array to get the names of your fields
  foreach ($field_list as $field) {
    $field_name = $field;
    $form[$field_name]['widget'][0]['value']['#placeholder'] = $form[$field_name]['widget'][0]['value']['#title'];
  }
}

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.