Saving Multiple Select in input

白昼怎懂夜的黑 提交于 2019-12-02 07:40:54

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:

<?php echo $this->Form->create('User'); ?>
    <?php echo $this->Form->input('Section.id'); ?>
    <?php echo $this->Form->input('User', array('multiple' => 'checkbox')); ?>
<?php echo $this->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.

CakePHP has the saveMany function, as mentioned in the documentation:

Model::saveMany(array $data = null, array $options = array())¶

This is HABTM relation, first of all you need have relation setup in SectionUser model. Then you can use saveAll() method to save all records at once.

Array
(
    [0] => Array
    (
        [user_id] => 33
        [section_id] => 9
    )

    [1] => Array
    (
        [user_id] => 33
        [section_id] => 10
    )
)

Make sure your data array is in above given format.

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