How do I change the edit form layout for a custom field type I created an Address custom field type, with two text fields (street and city).

When I add a new Address field on a content type, I get this form inside the edit page.



How can I change the layout of the form above?

For example, I would like to add some space between the Street text line and the City label, or display both fields on the same line.

This is the code for the AddressDefaultWidget class.

/**
 * Field type widget implementation.
 *
 * @FieldWidget(
 *   id = "AddressDefaultWidget",
 *   label = @Translation("Address select"),
 *   field_types = {
 *     "Address"
 *   }
 * )
 */
class AddressDefaultWidget extends WidgetBase {

  /**
   * Define the form for the field type.
   */
  public function formElement(
    FieldItemListInterface $items,
    $delta, 
    Array $element, 
    Array &amp;$form, 
    FormStateInterface $formState
  ) {

    // Street

    $element['street'] = [
      '#type' =&gt; 'textfield',
      '#title' =&gt; t('Street'),
      '#default_value' =&gt; isset($items[$delta]-&gt;street) ? 
          $items[$delta]-&gt;street : null,
      '#empty_value' =&gt; '',
      '#placeholder' =&gt; t('Street'),
    ];

    // City

    $element['city'] = [
      '#title' =&gt; t('City'),
      '#type' =&gt; 'textfield',
      '#default_value' =&gt; isset($items[$delta]-&gt;city) ? 
          $items[$delta]-&gt;city : null,
      '#empty_value' =&gt; '',
      '#placeholder' =&gt; t('City'),
    ];

    return $element;
  }

}
This is off the top of my head, so there might be a few kinks.
The way I would do it would be to:


Add a new class to each of the form elements that your module produces
Create some CSS to pad the top/bottom of elements with this class
Tell Drupal to include this CSS file whenever the form elements are on the page


In your Widget file add the following to each element to add an additional class to the form elements.

'#attributes' =&gt; [
  'class' =&gt; 'address_widget_class',
],


To add CSS styles to a custom module, you will need to create a few files and directories.


module/module.libraries.yml
module/css/style.css


In your CSS file, add the following to add 10 pixels above and below each item.

.address_widget_class {
  margin: 10px 0;
}


Next, you need to tell Drupal that the CSS file exists. In the module.libraries.yml file, add the following code.

style_name:
  version: 1.x
  css:
    component:
      css/style.css: {}


Finally, to include the library when the element is used, add the following to your Widget.

$element['street']['#attached']['library'][] = 'module/style_name';