Saving Multiple Select in input

前端 未结 3 1427
攒了一身酷
攒了一身酷 2021-01-28 16:38

I have model for

  • user(id,name)
  • section(id,name)
  • section_users(id,user_id,section_id)

The admin adds all the users and sections

3条回答
  •  臣服心动
    2021-01-28 17:08

    As already mentioned, this is exaplained in the docs, please read them, and in case you don't understand them (which would be understandable as the HABTM section is a little confusing and requires some trial & error), tell us what exactly you are having problems with.

    http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm

    Based on the examples shown, the format for saving multiple X to Y should be

    Array
        (
            [Section] => Array
                (
                    [id] => 1
                )
            [User] => Array
                (
                    [User] => Array(3, 4)
                )
        )
    

    The corresponding form could look like this:

    Form->create('User'); ?>
        Form->input('Section.id'); ?>
        Form->input('User', array('multiple' => 'checkbox')); ?>
    Form->end('Add Users'); ?>
    

    And the data would be saved via the Section model, that way its modified column is being updated properly.

    public function addUsersToSection($id) {
        // ...
        if($this->request->is('post')) {
            if($this->Section->save($this->request->data)) {
                // ...
            } else {
                // ...
            }
        } else {
            $options = array(
                'conditions' => array(
                    'Section.' . $this->Section->primaryKey => $id
                )
            );
            $this->request->data = $this->Section->find('first', $options);
        }
    
        $users = $this->Section->User->find('list');
        $this->set(compact('users'));
    }
    

    Another way would be to restructure the array as shown by Vinay Aggarwal, that works fine, the only difference is that it requires saving through the join model, and consequently it doesn't update the Section models modified column.

提交回复
热议问题