Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

isValid() must be called after bind() to populate Collection elements in bound object #19

Open
weierophinney opened this issue Dec 31, 2019 · 1 comment

Comments

@weierophinney
Copy link
Member

The documentation suggests following workflow with a form :

class MyObject {
 public $id;
 public $items = [];
}

class SubObjectFieldset extends Fieldset
{
    public function __construct( $name = null, $options = [] )
    {
        parent::__construct('items');

        $this->setHydrator(new \Zend\Hydrator\ObjectProperty());

        $this->add([
            'name' => 'id',
            'type' => 'hidden',
        ]);

        $this->add([
            'name' => ’title',
            'type' => ’text',
        ]);
    }
}

class ObjectForm extends Form
{
    public function __construct( $name = null, $options = [])
    {
        parent::__construct($name, $options);

        $this->setObject( new Object() );
        $this->setHydrator( new \Zend\Hydrator\ObjectProperty() );

        $this->add([
            'name' => 'id',
            'type' => 'hidden',
        ]);

        $this->add([
            'name' => 'items',
            'type' => 'Zend\Form\Element\Collection',
            'options' => [
                'target_element' => [
                    'type' => SubObjectFieldset::class,
                ]
            ]
        ]);
...
    }
}

$o = $db->getObject();

$f = new MyForm();
$f->bind($o);

$data = $request->getPost();
if ( !$f->setData($data)->isValid() ) {
… do something
}

// at this point it is expected $o has been populated with post $data
// but it doesn’t happen
$db->saveObject($o); 

setData() call updates only MyObject->id, but not MyObject->items, even though $data provides respective values. If workflow is changed as following, then MyObject->items updated as well

$o = $db->getObject();

$f = new MyForm();
$f->bind($o);
$f->isValid(); // <— add validation here

$data = $request->getPost();
if ( !$f->setData($data)->isValid() ) {
… do something
}

// now $o has been populated with received data
$db->saveObject($o);

Originally posted by @isharfme at zendframework/zend-form#137

@ceadreak
Copy link

Damned !! You saved my night ...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants