0

我的数据库中有这张表,它输出以下内容:

array(
(int) 0 => array(
    'Price' => array(
        'id' => '1',
        'amount' => '20',
        'price' => '180.00',
        'type_id' => '1',
        'active' => 'a'
    )
),
(int) 1 => array(
    'Price' => array(
        'id' => '2',
        'amount' => '30',
        'price' => '232.50',
        'type_id' => '1',
        'active' => 'a'
    )
), 

...等等。

I need a drop down in my form that displays the amount and price together (ie. "20 @ 180.00"), but when selected, gets the "id" field.

我重新设计了一个名为 $prices 的新数组,所以它的输出是这样的......

array(
(int) 0 => array(
    'id' => '1',
    'amount' => '20',
    'price' => '180.00',
    'type_id' => '1',
    'active' => 'a',
    'display' => '20 @ 180.00'
),
(int) 1 => array(
    'id' => '2',
    'amount' => '30',
    'price' => '232.50',
    'type_id' => '1',
    'active' => 'a',
    'display' => '30 @ 232.50'

但是,我不确定该数组是否必要。

但主要问题是我不知道在表单选项中放置什么以使其选择“显示”字段。

echo $this->Form->input('Project.quantity', array(
  'options' => $prices[?????]['display']
));

只需添加

'options' => $prices

在下拉列表中显示很多东西(http://f.cl.ly/items/1e0X0m0D1f1c2o3K1n3h/Screen%20Shot%202013-05-08%20at%201.13.48%20PM.png)。

有没有更好的方法来做到这一点?

4

2 回答 2

3

You can use virtual fields.

In your model:

public $virtualFields = array(
  'display' => 'CONCAT(amount, " @ ", price)'
);

In the controller:

$prices = $this->Price->find('list', array(
  'fields' => array('id', 'display')
));
于 2013-05-08T17:30:14.727 回答
0

Two ways to do this.

  1. You said you reworked you array to $prices. Then, change that rework so the $prices array looks like this

    array('1' => '4 @ 6',
          /*id*/ => /*price*/
          /*etc*/);
    

    and then pass it to the form

    echo $this->Form->input('Project.quantity', array(
      'options' => $prices
    ));
    
  2. For a simple dropdown, retrieve the data with a find('list'). That will give you an array like the one you need to make a dropdown. To change the display field, create a virtual field like this in the model

    public $virtualFields = array("display_price"=>"CONCAT(amount, ' @ ' ,price)");
    public $displayField = 'display_price';
    

    And that way you don't have to rework your array. If you have other drowpdowns of the same model in other forms, note that those will also change. That's the advantage of doing that in the model... Or disadvantage, if you only want to do it in one part... Like almost everything, it depends on what your need are :)

于 2013-05-08T17:29:29.507 回答