CakePHP Sort Select of IDs

时间:2017-06-19 13:54:02

标签: php cakephp

I have a select on a form which I want to populate with users for the user to choose.

Sounds simple however the problem I'm getting is with the IDs, example (my list is a lot longer and comes from MySQL DB):

$users = [
    1 =>  "Zelda",
    2 =>  "Apple"
]

sort result: (now IDs are invalid)

 $users = [
        1 =>  "Apple"
        2 =>  "Zelda",
    ]

If I sort the list then the IDs get moved which means I can't then call the Cake Save method in my controller on it, I've tried added a sort to my:

$users = $this->User->find('list', [
        'recursive' => -1,
        'conditions' => [
            'User.status' => 1,
            'User.id > ' => 1,
            'NOT' => [
                'User.phone' => null
            ]
        ],
        'fields' => [
            'User.full_name'
        ],
        'order' => [
            'User.full_name'
        ]
    ]);

I additionally have another field with a similar problem, it uses the text from two fields to map to a single ID, so I've concatenated the text together but I'm struggling to get the list sorted using the form helper but to keep the ID association.

This must be a really common problem seeing you can't sort a numerically indexed array and keep the IDs in the same position, so what am I missing?

Many thanks in advance.

1 个答案:

答案 0 :(得分:2)

我确定你没有使用id,你只选择'User.full_name'一个你应该选择id的字段:

        'fields' => [
            'User.id',
            'User.full_name'
        ]

是获得2个字段的方法,您只需订购的是默认数组的编号不是id。