php - ZF2 + Doctrine 2: Hydrate related objects via ZF2 Form -
our application (zend framework 2 + doctrine 2) has order
entity references related objects billingaddress
, on. have implemented rest api create , update orders. data passed api associative array , data of referenced objects can encapsulated inside array. i. e. data received order
api looks this
$data = [ // attribute of order entity 'remarks' => 'urgent order', // data of referenced billingaddress 'billing_address' => [ 'firstname' => 'barry', 'lastname' => 'fooman' ] ];
first thing note fact given billingaddress
can either new or existing one! in latter case id
part of billing_address
data.
using doctrineobject
hydrator
$hydrator = new doctrineobject($entitymanager); $hydrator->hydrate($order, $data);
doctrine takes care of updating or creating referenced objects automagically. how doing far: take received data, little processing sanitize , validate data , call hydrator.
however want use zend\form\form
easy sanitizing of received data. setting form
simple attributes of order pretty easy
class orderform extends \zend\form\form { public function __construct() { parent::__construct('order'); $this ->add([ 'name' => 'remarks', 'type' => 'text' ]); } }
but struggle referenced objects. how set form referenced objects created or updated doctrine using hydrator directly? have create "sub-form/fieldset"?
yes, can create fieldset businessaddress entity , add orderform.
use zend\form\fieldset; class businessaddressfieldset extends fieldset { public function __construct($entitymanager) { parent::__construct('businessaddress'); $this->add(array( 'name' => 'firstname', 'type' => 'zend\form\element\text', 'options' => array( 'label' => 'first name', ), 'attributes' => array( 'type' => 'text', ), )); $this->add(array( 'name' => 'lastname', 'type' => 'zend\form\element\text', 'options' => array( 'label' => 'last name', ), 'attributes' => array( 'type' => 'text', ), )); } }
and add field set orderform:
class orderform extends \zend\form\form { public function __construct() { parent::__construct('order'); // add fields $this->add(new businessaddressfieldset()); } }
make sure name of fieldset set, match name of reference , set form hydrator.
Comments
Post a Comment