CakePHP:将setDisplayField设置为虚拟字段

时间:2019-05-18 17:06:36

标签: php mysql cakephp

我正在关注CakePHP 3.7的文档,以便在选择输入控件中显示虚拟字段。

DeliveryNotesTable.php

public function initialize(array $config)
{
    parent::initialize($config);

    $this->setTable('delivery_notes');
    $this->setDisplayField('reference');
    $this->setPrimaryKey('id');

    $this->belongsTo('Customers', [
        'foreignKey' => 'customer_id'
    ]);
    $this->belongsTo('ShipmentReasons', [
        'foreignKey' => 'shipment_reason_id'
    ]);
    $this->belongsTo('ShipmentMethods', [
        'foreignKey' => 'shipment_method_id'
    ]);
    $this->hasMany('ItemsDeliveryNotes', [
        'foreignKey' => 'delivery_note_id'
    ]);
    $this->hasMany('ItemOrders', [
        'foreignKey' => 'delivery_note_id'
    ]);
}

protected function _getReference()
{
    return $this->deliveryNoteNumber . ' ' . $this->deliveryNoteDate;
}

我在DeliveryNote.php中公开了虚拟字段:

class DeliveryNote extends Entity
{
    protected $_accessible = [
        'customer_id' => true,
        'shipment_reason_id' => true,
        'deliveryNoteNumber' => true,
        'deliveryNoteDate' => true,
        'shipment_method_id' => true,
        'number_of_packages' => true,
        'weight' => true,
        'customer' => true,
        'shipment_reason' => true,
        'shipment_method' => true,
        'items_delivery_notes' => true
    ];

    protected $_virtual = [
        'reference'
    ];
}

在我的控制器中,我加载了相关数据:

public function add($id)
{
    $itemOrder = $this->ItemOrders->newEntity();
    $itemOrder['order_id'] = $id;
    if ($this->request->is('post')) {
        $itemOrder = $this->ItemOrders->patchEntity($itemOrder, $this->request->getData());
        if ($this->ItemOrders->save($itemOrder)) {
            $this->Flash->success(__('The {0} has been saved.', 'Item Order'));

            return $this->redirect(['controller' => 'orders', 'action' => 'index']);
        }
        $this->Flash->error(__('The {0} could not be saved. Please, try again.', 'Item'));
    }
    $orders = $this->ItemOrders->Orders->find('list', ['limit' => 200]);
    $itemOrdersTypes = $this->ItemOrders->ItemOrdersTypes->find('list', ['limit' => 200]);
    $products = $this->ItemOrders->Products->find('list', ['limit' => 200, 'order' => ['Products.code' => 'ASC']]);
    $itemOrdersStates = $this->ItemOrders->ItemOrdersStates->find('list', ['limit' => 200]);
    $deliveryNotes = $this->ItemOrders->DeliveryNotes->find('list');
    $this->set(compact('itemOrder', 'orders', 'itemOrdersTypes', 'products', 'itemOrdersStates', 'deliveryNotes'));
}

最后,在模板中,创建选择控件:

<?= $this->Form->control('delivery_note_id', ['options' => $deliveryNotes, 'empty' => true]); ?>

,但为空,不显示任何项目。 相反,如果我设置:

$this->setDisplayField('id');

或其他任何字段,都将正确填充选择控件。 我在创建这个虚拟领域时想念什么?

1 个答案:

答案 0 :(得分:1)

您的protected function _getReference()方法必须在DeliveryNote实体类中设置

阅读:https://book.cakephp.org/3.0/en/orm/entities.html#creating-virtual-fields