CakePHP select input : is setting a display member

2019-09-13 08:43发布

问题:

I have this form input:

echo $this->Form->input('category_id',array('label'=>'Catégorie','type'=>"select",'options'=>$categories,'empty'=>false));

Now, $category is filled with those informations:

Array
(
[0] => Array
    (
        [categories] => Array
            (
                [id] => 1
                [nom] => Autre
            )

    )

[1] => Array
    (
        [categories] => Array
            (
                [id] => 2
                [nom] => Véhicule
            )

    )

[2] => Array
    (
        [categories] => Array
            (
                [id] => 3
                [nom] => Audio/video
            )

    )

)

I would like that the Select input shows only the "nom" field (name), but that it sends the ID when the form is submitted. Is that possible in CakePHP? I've been crawling through Google and CakePHP's doc and forums for a while without success :-/

Thank you in advance guys and have a nice day!

回答1:

Cakephp uses a single dimension array for select options. You change your your to single dimension with id as your key and nom as text of option tag and then pass it to options key:

$categories = Set::combine($categories,'{n}.categories.id','{n}.categories.nom');


回答2:

You should respect Cakephp conventions. Remplace "nom" by "name" in your database and cakephp will do it automatically if your associations have been well done.