Home > other >  Vaadin formlayout won't centre
Vaadin formlayout won't centre

Time:02-13

I'm building a registration form in Vaadin 22 and I want the FormLayout to be in the centre of the page horizontally.

The headlingLabel centres correctly but the form is always to the left hand side of the page. If I remove the setMaxWidth of the form the form fills the full width of the page.

package dev.onepub.ui.views.authed;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;

import dev.onepub.dao.DaoMember;
import dev.onepub.entity.enums.ActionEnum;
import dev.onepub.session.MemberSession;
import dev.onepub.ui.DefaultView;
import dev.onepub.ui.OnePubLayout;
import dev.onepub.ui.crud.Access;

/// Place holder for the re-registration process.

@Access(required = ActionEnum.notRequired)
@Route(value = "Register", layout = OnePubLayout.class)
public class RegistrationView extends VerticalLayout
{
    private transient Logger logger = LogManager.getLogger();

    private static final long serialVersionUID = 1L;
    public static final String NAME = "Register";
    public static final String LABEL = "register";

    TextField firstName = new TextField("First name");
    TextField lastName = new TextField("Last name");
    TextField email = new TextField("Preferred Email");
    TextField publisher = new TextField("Organisation Name");

    Checkbox subscribe = new Checkbox("Subscribe to periodic newsletters for product features, tips and tricks.");
    Checkbox terms = new Checkbox();

    Button signup = new Button("Signup");

    private Binder<Registration> binder = new Binder<>(Registration.class);

    public RegistrationView()
    {

        this.setSizeFull();
        // this.setMargin(false);

        HorizontalLayout heading = new HorizontalLayout();
        heading.setWidth("100%");
        Label headingLabel = new Label("Please confirm the following details");
        this.add(headingLabel);

        final var form = new FormLayout();
        this.add(form);
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.START);
        form.setMaxWidth("800px");

        terms.setLabelAsHtml(
                "I agree to both the <a href='https://www.onepub.dev/terms' target='_blank'>terms and conditions</a>, and the <a href='https://www.onepub.dev/privacy' target='_blank'>privacy policy.</a>");

        form.add(firstName, lastName, email, publisher, subscribe, terms, signup);
        form.setColspan(email, 2);
        form.setColspan(publisher, 2);
        form.setColspan(subscribe, 2);
        form.setColspan(terms, 2);
        form.setColspan(signup, 2);

        form.setResponsiveSteps(
                // Use one column by default
                new ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new ResponsiveStep("500px", 2));

        binder.bindInstanceFields(this);

        final var member = MemberSession.getCurrent().loggedInMember;

        final var registration = new Registration(member);
        binder.setBean(registration);

        signup.addClickListener(event -> save());

    }

    private void save()
    {
        Registration registration = binder.getBean();
        final var member = new DaoMember().findByEntity(MemberSession.getCurrent().loggedInMember);
        member.setFirstname(registration.firstName);
        member.setSurname(registration.lastName);
        member.setPreferredEmail(registration.email);
        member.getPublisher().setName(registration.publisher);
        member.setAcceptedTerms(terms.getValue());
        member.setSubcribed(subscribe.getValue());

        UI.getCurrent().navigate(DefaultView.class);

    }

}

CodePudding user response:

Add this form.getStyle().set("align-self", "center");

Explanation

If you inspect the vaadin-form-layout element, you'll discover 2 things:

  1. It automatically sets align-self to stretch which basically makes it try to fill up the available space of the parent.
  2. max-width: 100%

You can override those Behavior by setting align-self to center and setting a width to the form using form.setWidth("WIDTH");.

CodePudding user response:

Based on @styl3r response I found that I just need to add

setAlignSelf(Alignment.CENTER, form);
setJustifyContentMode(JustifyContentMode.START);

This avoids directly playing with styles.

So the full answer is:

package dev.onepub.ui.views.authed;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.vaadin.flow.component.UI;
import com.vaadin.flow.component.button.Button;
import com.vaadin.flow.component.checkbox.Checkbox;
import com.vaadin.flow.component.formlayout.FormLayout;
import com.vaadin.flow.component.formlayout.FormLayout.ResponsiveStep;
import com.vaadin.flow.component.html.Label;
import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
import com.vaadin.flow.component.orderedlayout.VerticalLayout;
import com.vaadin.flow.component.textfield.TextField;
import com.vaadin.flow.data.binder.Binder;
import com.vaadin.flow.router.Route;

import dev.onepub.dao.DaoMember;
import dev.onepub.entity.enums.ActionEnum;
import dev.onepub.fields.validators.EmailValidator;
import dev.onepub.session.MemberSession;
import dev.onepub.ui.CheckboxWithError;
import dev.onepub.ui.DefaultView;
import dev.onepub.ui.OnePubLayout;
import dev.onepub.ui.crud.Access;
import dev.onepub.ui.crud.PublicView;

/// Place holder for the re-registration process.

@Access(required = ActionEnum.notRequired)
@Route(value = "Register", layout = OnePubLayout.class)
public class RegistrationView extends VerticalLayout implements PublicView
{
    @SuppressWarnings("unused")
    private transient Logger logger = LogManager.getLogger();

    private static final long serialVersionUID = 1L;
    public static final String NAME = "Register";
    public static final String LABEL = "register";

    TextField firstName = new TextField("First name");
    TextField lastName = new TextField("Last name");
    TextField email = new TextField("Preferred Email");
    TextField publisher = new TextField("Organisation Name");

    Checkbox subscribe = new Checkbox(
            "Subscribe to periodic newsletters for product features, tips and tricks. (No more than once a month)");
    CheckboxWithError terms = new CheckboxWithError();

    Button signup = new Button("Signup");

    private Binder<Registration> binder = new Binder<>(Registration.class);

    public RegistrationView()
    {
        this.setSizeFull();
        // this.setMargin(false);

        HorizontalLayout heading = new HorizontalLayout();
        heading.setWidth("100%");
        Label headingLabel = new Label("Please confirm the following details");
        this.add(headingLabel);

        final var form = new FormLayout();
        setAlignSelf(Alignment.CENTER, form);
        setJustifyContentMode(JustifyContentMode.START);
        this.add(form);
        this.setAlignItems(Alignment.CENTER);
        this.setJustifyContentMode(JustifyContentMode.START);
        form.setMaxWidth("800px");

        terms.setLabelAsHtml(
                "I agree to both the <a href='https://www.onepub.dev/terms' target='_blank'>terms and conditions</a>, and the <a href='https://www.onepub.dev/privacy' target='_blank'>privacy policy.</a>");

        form.add(firstName, lastName, email, publisher, subscribe, terms, signup);
        form.setColspan(email, 2);
        form.setColspan(publisher, 2);
        form.setColspan(subscribe, 2);
        form.setColspan(terms, 2);
        form.setColspan(signup, 2);

        form.setResponsiveSteps(
                // Use one column by default
                new ResponsiveStep("0", 1),
                // Use two columns, if layout's width exceeds 500px
                new ResponsiveStep("500px", 2));

        binder.bindInstanceFields(this);

        binder.forField(email).withValidator(new EmailValidator("Note a valid email address"))
                .bind("email");
        binder.forField(terms).withValidator((v) -> v == true, "You must accept the Terms and Conditions")
                .bind("terms");

        final var member = MemberSession.getCurrent().preRegistrationMember;

        final var registration = new Registration(member);
        binder.setBean(registration);

        signup.addClickListener(event -> save());

    }

    private void save()
    {
        Registration registration = binder.getBean();
        final var status = binder.validate();
        if (status.isOk())
        {
            final var member = new DaoMember().findByEntity(MemberSession.getCurrent().loggedInMember);
            member.setFirstname(registration.firstName);
            member.setSurname(registration.lastName);
            member.setPreferredEmail(registration.email);
            member.getPublisher().setName(registration.publisher);
            member.setSubcribed(subscribe.getValue());

            member.setAcceptedTerms(terms.getValue());

            MemberSession.getCurrent().preRegistrationMember = null;

            UI.getCurrent().navigate(DefaultView.class);
        }

    }

}
  • Related