3

I need an address field that allow the user to encode only a country OR a country with some other fields he could choose freely.

I other words, I need an address field without any required field.

To do so, I have tried to alter the widget as explained in some tutorials:

function mymodule_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'address') {
    $element['name_block']['name_line']['#required'] = FALSE;
    $element['street_block']['thoroughfare']['#required'] = FALSE;
    $element['locality_block']['dependent_locality']['#required'] = FALSE;
    $element['locality_block']['locality']['#required'] = FALSE;
    $element['locality_block']['administrative_area']['#required'] = FALSE;
    $element['locality_block']['postal_code']['#required'] = FALSE;
  }

}

Unfortunately, the $element variable is not yet populated with the subfields...

  • Hi @Baud. Were you able to make address fields optional based on a specific field in custom module for D8? – Prerit Mohan Apr 14 at 5:37
  • Just use the last version of the date module. In the settings of the date field you want to add to a content type, you will find all the needed options to make some fields optional. – Baud Apr 14 at 9:45
  • Date or address? And I want to make the address fields optional based on the value of another field in the custom form. – Prerit Mohan Apr 14 at 14:26
  • Sorry, you should read "address" and not "date". Add an address field, then go to the settings page:admin/structure/types/manage/client/fields/node.client.field_client_adresse (for a content type named client and a field named field_client_adresse) the you be able to change the optional field under Field overrides at the bottom. – Baud Apr 15 at 17:00
  • Thank you but I need to make them option if the payment option is of type Cheque only. Not always optional. – Prerit Mohan Apr 15 at 19:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.