Symfony 1.4表单:包含从关系到表单的数据


Symfony 1.4 Forms: Include Data from Relation to Form

我有以下两个模型的示例模式OrderDetail和Item,多对一关系:

OrderDetail:
  columns:
    invoice_id: { type: integer, notnull: true }
    item_id: { type: integer, notnull: true }
    quantity: { type: integer, notnull: true }
    transaction_price: { type: integer }
    currency: { type: string(50), default: peso }
  relations:
    Invoice: { type: one, local: invoice_id, foreign: invoice_id }
    Item: { type: one, local: item_id , foreign: item_id }
  indexes:
    invoice_to_item:
      fields: [item_id, invoice_id]
      type: unique
Item:
  actAs: { Timestampable: ~, SoftDelete: ~ }
  columns:
    item_id: { type: integer, autoincrement: true, primary: true }
    item_name: { type: string(100), notnull: true }
    description: { type: text, notnull: true }
    part_number: { type: string(50) }
    size: { type: string(50) }
    unit: { type: string(10) }
    in_stock: { type: integer, notnull: true }
    in_transit: { type: integer, notnull: true }
    released: { type: integer, notnull: true }
    borrowed: { type: integer, notnull: true }
    borrower_name: { type: string }
    item_type_id: { type: integer, notnull: true }
  relations:
    OrderDetails: { type: many, class: OrderDetail, local: item_id, foreign: item_id }
    Prices: { type: many, class: Price, local: item_id, foreign: item_id }

在我的表单中,我想包含Item表中的信息,如item_namein_stock。我想要做的只是显示与表单相关的Item表中的数据。为了清晰和组织,我想在表单对象中包含这些信息。我想在我的表单中做这样的事情:

echo $form[$number]['Item']['part_number']->getValue()
// where $number is the index of the OrderDetail in the form and key 'Item' contains data for the Item related to this OrderDetail.

我尝试在OrderDetail中嵌入Item关系,例如:

class OrderDetailForm extends BaseOrderDetailForm {
    public function configure() {
        // some config here...
        $this->embedRelation('Item');
    }
}

这样做的问题是,当我保存表单时,Item对象也被验证和保存。我只是将这些信息用于显示目的。下面是一个我想要的表单和我想要做的事情的粗略示例:

OrderDetail: 1
Item: Headset
In Stock: 5pcs
Quantity: [input field here that can be changed by the user]
如果有什么不清楚的,请让我知道。另外,如果你能提出一个更好的方法,我将不胜感激。

如果orderdetailform被嵌入到InvoiceForm中,并且您希望从中访问Item对象。那么我建议你在模板中使用这样的内容:

// apps'myApp'modules'myModule'templates'editSuccess.php
$orderDetailForms = $invoiceForm->getEmbeddedForms();
foreach ($orderDetailForms as $key => $form) {
    $item = $form->getObject()->getItem();
    echo 'Item name: ' . $item->getItemName() . '<br />';
    echo 'In stock: ' . $item->getInStock() . '<br />';
    echo $form;
}

这里要做的事情是确保在执行查询时检索Item对象和OrderDetail对象。因为这一行($form->getObject()->getItem())每次都会有效地执行数据库查询。