CakePHP Form Dropdown

我怕爱的太早我们不能终老 提交于 2020-01-06 12:27:18

问题


I've got this table in my database that outputs this:

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'
    )
), 

...And so on.

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.

I reworked a new array called $prices so it outputs like so...

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'

However, I'm not sure if that array is necessary.

But the main problem is that I don't know what to put in the Form options to make it select the "display" field.

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

Simply adding the

'options' => $prices

displays a lot of stuff in the drop down (http://f.cl.ly/items/1e0X0m0D1f1c2o3K1n3h/Screen%20Shot%202013-05-08%20at%201.13.48%20PM.png).

Is there a better way of doing this?


回答1:


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')
));



回答2:


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 :)



来源:https://stackoverflow.com/questions/16446524/cakephp-form-dropdown

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!