Skip to content
This repository was archived by the owner on Jan 8, 2020. It is now read-only.
This repository was archived by the owner on Jan 8, 2020. It is now read-only.

There is no simple way to clear form collection if form is bound to an object. #7298

Closed
@Redigast13

Description

@Redigast13

I use doctrine 2 with ZF2 forms. When I submit a form I bind doctrine entity to the form. Then I set POST data to the form. And if the form is valid I save the data to DB. I think it is a normal way to work with ZF2 forms. I use this code when user wants to update "user" entity.

// $form has form collection "roles"
$form->bind($entity); // $entity->roles is not empty
$form->setData($someData); // $someData['roles'] is empty array
if ($form->isValid()) {
    $form->get('roles')->getCount(); // 2(!) it is not empty!
    saveToDb($entity);
}
return $form;

Do you think that this code is corrrect? No. Because there is a form collection in this form. And $entity has two roles now. And user wants to remove all roles from "user" entity. And this beautiful framework can't clear form collection. (populateValues() does nothing if data is empty https://github.com/zendframework/zf2/blob/master/library/Zend/Form/Element/Collection.php#L199 )

So, what should I do? I should find all form collections in this form and clear this collection in doctrine entity before I bind this entity to the form.

foreach ($form->getFieldsets() as $fieldset) {
    if ($fieldset instanceof Collection) {
        $name = $fieldset->getName();
        if (empty($someData[$name])) {
            $methodName = 'set' . ucfirst($name);
            call_user_func([$entity, $methodName], []);
        }
    }
}
$form->bind($entity); // now $entity->roles is empty
$form->setData($someData); // $someData['roles'] is empty array
if ($form->isValid()) {
    $form->get('roles')->getCount(); // 0
    saveToDb($entity);
}
return $form;

Very elegant! Here is the same issue #4492 . It opened TWO years ago. What happened with ZF2? Is this project dead?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions