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

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

Open
isharfme opened this issue Feb 5, 2017 · 1 comment

Comments

@isharfme
Copy link

isharfme commented Feb 5, 2017

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);
@weierophinney
Copy link
Member

This repository has been closed and moved to laminas/laminas-form; a new issue has been opened at laminas/laminas-form#19.

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

No branches or pull requests

2 participants