hydrating multiple objects from fieldsets ZF2

2019-09-14 10:14发布

问题:

I have a problem with hydrating the objects in ZF2.

I have a form for saving either the organization-related info or person-related info into the database. The user makes the choice: save either organization or person. Just 1 form for all html inputs.

In ZF2, I created 2 fieldsets. In each fieldset class, I use setHydrator(new ClassMethods(false)) and setObject(new <objectForHydration>). The 2 fieldsets are included into the form with the following code:

    $this->add([
        'type' => 'Parties\Form\Fieldsets\RegisterOrganizationFieldset',
        'options' => [
            'use_as_base_fieldset' => true,
        ],
    ]);

    $this->add([
        'type' => 'Parties\Form\Fieldsets\RegisterPersonFieldset',
        'options' => [
            'use_as_base_fieldset' => true,
        ],
    ]);

I want RegisterOrganizationFieldset to hydrate OrganizationObject, and RegisterPersonFieldset to hydrate PersonObject.

I thought of hydrating both objects at the same time because this won't introduce conditionals into the form class. The problem is the hydration takes place just 1 object depending on which fieldset has use_as_base_fieldset = true. If both fieldsets have use_as_base_fieldset = true, the fieldset later in the code (RegisterPersonFieldset) hydrates only its respective object.

Could you tell how to hydrate both objects? Maybe how to hydrate objects in a better way?

EDIT:

As @jcropp pointed, I use Person and Organization as Parties that are independent entities sharing only Id property.

回答1:

One way to hydrate two objects at the same time is to make them both the same object.

It is not clear from your question whether 1) a person who is registering is a member of a registering organization, or 2) "parties" are registering, and a party can be either an organization or a person. Here are some answers for both cases:

If persons are members of organizations in your data structure, a method for hydrating both at the same time is to treat the persons data as "collections" of the organization data elements. This method utilizes relationships between the fieldsets to create a single dataset in which both the organization data and the person data can be edited together. See the ZF2 Manual.

If your intent is to register individual parties, and a party can be either an organization or a person, a method for hydrating one or the other in the same form is to use table inheritance. In single table inheritance you would have a single table (and a single fieldset) for both types of parties, and a selection between the person or organization type would indicate whether data should be entered into the organization fields or the person fields of the table. In multiple table inheritance, you would create a party table that related to an organization table and to a person table; and organization and person fieldsets would extend the party fieldset.