简体   繁体   中英

Cakephp $this->request->data returns id of select field instead of value which is needed and shown in the select field

I have a CakePHP controller like this:

$this->loadModel('Project');

$list2 = $this->Project->find( 'list', array(
    'fields'     => array('Project.project'),
    'conditions'    => array('Project.user_id' => $userId)
));

$this->set($list2, 'list2');

$this->loadModel('Distance');

if(!empty($this->request->data)){    
    $this->Distance->create();
    if ($this->Distance->save($this->request->data)) {
        $this->Session->setFlash('Saved.');
        //  $this->redirect(array('action' => 'index'));
    } else {
        $this->Session->setFlash('FAILED');
    }
}else{
    //  $this->Session->setFlash('test');
}

and a view like this:

echo $this->Form->input('Distance.project', array('options' => $list2, 'label' => false, 'empty' => '(choose one)'  ;

But I get inserted to the database the id of the project instead of the project name. I never have such problems working with the fields - just with a list of data.

Any idea why it happens?

It's normal ... The $list2 it's and array ... and the values of the options are the indexes from that array.

If you want to insert only the project name you need to change $list2 with $list2['project_name']. You need to remove or replace the indexes of $list2.

LE: take iexiak example. He change also the code for you.

 $list2 = $this->Project->find( 'list', array(

                    'fields'     => array('Project.project'),
                     'conditions'    => array('Project.user_id' => $userId)
                 )

         );

This is because $list2 automatically creates a list of ID => project; and when you use that as input for your form it automatically creates the drop down to reflect this. This is generally the best practice, to link to ID's instead of to descriptions, as ID's do not change as often. The below should get you exactly what you want though:

 $list2 = $this->Project->find( 'list', array(

                    'fields'     => array('Project.project','Project.project'),
                     'conditions'    => array('Project.user_id' => $userId)
                 )

         );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM