5

Using Vaadin 12 with FormLayout and labels left of input fields.

I want to set the width of the label column. How to achieve this, using the Java API?

rmuller
  • 12,062
  • 4
  • 64
  • 92

2 Answers2

5

If you are using FormItem.addToLabel(..) method to set the label content, then the width of that is controlled in FormItem by custom property --vaadin-form-item-label-width (see more: https://vaadin.com/components/vaadin-form-layout/html-api/elements/Vaadin.FormItemElement ) The default value is 8em. So you can set is wider e.g. with:

formItem.getElement().getStyle().set("--vaadin-form-item-label-width", "10em");

You cannot create instance of FormItem directly but it is returned when adding component to FormLayout:

FormItem formItem = formlayout.addFormItem(component, "label text");
blekione
  • 10,152
  • 3
  • 20
  • 26
Tatu Lund
  • 9,949
  • 1
  • 12
  • 26
  • 2
    Thanks. This works as you explained @ `FormItem` level. But i want to set it once for the `FormLayout` (and/or globally for the whole app). Is this possible? – rmuller Jan 29 '19 at 16:10
3

For setting the individual FormItem label width and/or a more dynamic approach, see both answer @TatuLund and his comment for this solution.

For setting the label with in the whole Form, use @HtmlImport("frontend://styles/shared-styles.html")

And in shared-styles.html add this fragment:

<dom-module theme-for="vaadin-form-item" id="custom-form-item">
    <template>
        <style>     
            :host {
                --vaadin-form-item-label-width: 15em;  
            }
        </style>
    </template>
</dom-module>

Gotcha (for me): theme-for="vaadin-form-item" instead of theme-for="vaadin-form-layout"



UPDATE for Vaadin Flow v14+ (tested with v14.1.3)

Create form-item.css in PROJECT_DIR/frontend/styles/ with content:

   :host {
        --vaadin-form-item-label-width: 15em;
    }

Add annotation in top-level routing class (in my case the master layout class):

@CssImport(value = "./styles/form-item.css", themeFor = "vaadin-form-item")

Also see https://vaadin.com/docs/v14/flow/theme/migrate-p2-to-p3.html and https://stackoverflow.com/a/57553974/868941.

rmuller
  • 12,062
  • 4
  • 64
  • 92
  • 1
    Yes, this is one approach and more effective way to implement this. The other version could have been to extend FormItem and set property in the constructor. This version is handier if you want to change the width dynamically and your version when it is more static. – Tatu Lund Jan 30 '19 at 07:31