2016-11-08 13 views
0

私たちのアプリケーション(Zend Framework 2 + Doctrine 2)は、BillingAddressなどの関連オブジェクトを参照するOrderエンティティを持っています。注文を作成および更新するためのREST APIを実装しました。データはこのAPIに連想配列として渡され、参照されるオブジェクトのデータはこの配列内にカプセル化されます。 I. E.はOrder APIが受信したデータがどのように見えるこれについて注意するには、このZF2 + Doctrine 2:ZF2フォームによる水和関連オブジェクト

$data = [ 
    // This is an attribute of the Order entity itself 
    'remarks' => 'Urgent order', 
    // This is the data of the referenced BillingAddress 
    'billing_address' => [ 
     'firstname' => 'Barry', 
     'lastname' => 'Fooman' 
    ] 
]; 

まず最初はBillingAddress与えられたが、新規または既存のもののいずれかとすることができるという事実です!後者の場合、idbilling_addressデータの一部です。

Doctrineが更新または自動的に参照されるオブジェクトを作成するの面倒をDoctrineObjectハイドレーター

$hydrator = new DoctrineObject($entityManager); 
$hydrator->hydrate($order, $data); 

を使用します。これまでのところ、これまでのやり方です:受信したデータを取り、少しの処理をしてデータをサニタイズして検証し、ハイドレーターに電話してください。

ただし、受信データの簡単な消毒のためにZend\Form\Formを使用します。注文の単純属性のFormを設定すると、

class OrderForm 
    extends \Zend\Form\Form 
{ 
    public function __construct() 
    { 
     parent::__construct('order'); 

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

非常に簡単です。しかし、私は参照しているオブジェクトに苦労しています。ハイドレーターを直接使うようにDoctrineによって参照オブジェクトが作成または更新されるようにフォームを設定するにはどうすればよいですか? 「サブフォーム/フィールドセット」を作成する必要がありますか?

答えて

1

はい、BusinessAddressエンティティのフィールドセットを作成し、それを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', 
     ), 
    )); 
} 

} 

そしてあなたのOrderFormにフィールドセットを追加します。

class OrderForm 
extends \Zend\Form\Form 
{ 
    public function __construct() 
    { 
     parent::__construct('order'); 

     // add fields 

     $this->add(new BusinessAddressFieldset()); 

    } 
} 

が設定したフィールドセットの名前は、参照の名前と一致することを確認し、フォームのハイドレーターを設定していること。

+0

アドバイスをいただきありがとうございます。私は現在、実装に取り​​組んでおり、完了した時点で正しい答えを記入します。すべてが動作します – Subsurf

+0

これはトリックでした – Subsurf

関連する問題