How set the label width of a FormLayout in Vaadin Flow?
Asked Answered
B

2

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?

Berar answered 28/1, 2019 at 20:48 Comment(0)
M
6

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");
Mildred answered 29/1, 2019 at 9:36 Comment(1)
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?Berar
B
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://mcmap.net/q/610813/-where-should-i-place-my-vaadin-10-static-files.

Berar answered 29/1, 2019 at 20:33 Comment(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.Mildred

© 2022 - 2024 — McMap. All rights reserved.