4.3.4. One-to-One Composition with a Single Editor

It is often convenient to edit the One-to-One composition in one single editor. Let’s see how it can be implemented taking the Customer and the CustomerDetails relationship as an example.

  • customer-edit.xml descriptor contains the main customerDs and the nested detailsDs datasources:

    <dsContext>
        <datasource id="customerDs"
                    class="sample.entity.Customer"
                    view="customer-view">
            <datasource id="detailsDs"
                        property="details"/>
        </datasource>
    </dsContext>

    Fields for editing both entities are grouped into one fieldGroup, where some fields are bound to the nested datasource:

    <fieldGroup id="customerGroup"
                datasource="customerDs">
        <column width="200px">
            <field property="name"/>
            <field property="email"/>
            <field datasource="detailsDs"
                   property="address"
                   rows="3"/>
            <field datasource="detailsDs"
                   property="note"
                   rows="3"/>
        </column>
    </fieldGroup>
  • In the CustomerEdit controller we override the initNewItem() method. It will create a CustomerDetails instance and link it to the new Customer instance when the latter is just created:

    @Inject
    private Metadata metadata;
    
    @Override
    protected void initNewItem(Customer customer) {
        customer.setDetails(metadata.create(CustomerDetails.class));
    }

    Finally, let’s handle the situation when a user clicks Create and then wants to close the editor without changing anything. This user will be asked for saving changes, as the detailsDs datasource already contains an empty instance and isModified() method of the AbstractEditor will always return true. To prevent the appearance of confirmation dialog, we should make isModified() consider changes only in the master datasource:

    @Override
    public boolean isModified() {
        return customerDs.isModified();
    }

Now, both linked entities can be created and edited in one editor screen.