V
V
Victor Umansky2017-03-30 00:18:24
Yii
Victor Umansky, 2017-03-30 00:18:24

How to save data from the checkbox through the model?

Good night all.
I have such a schema, I have a profile, category, profile_has_category table.
profile
id | user_id | category_id | ... | ...
category
id | parent_id | title | ... | ...
profile_has_category
id | user_id | category_id | ...
The user selects the category(s) for himself, what he has chosen should be saved to the profile_has_category table, then I get the id from the profile_has_category and save it in the profile: category_id
model

public function updateProfile()
    {
        $id = Yii::$app->user->id;
        $profile = ($profile = Profile::findOne(['user_id' => $id])) ? $profile : new Profile();
        $profile->user_id = Yii::$app->user->id;
        
         ....
         // не могу принять post в моделе 
         if (Yii::$app->request->isPost) {
            VarDumper::dump(Yii::$app->request->post(), 11, 1);
            die;
        }

        return $profile->save() ? true : false;
    }

controller
public function actionProfile()
    {
        $id = Yii::$app->user->id;
        $model = ($model = Profile::findOne(['user_id' => $id])) ? $model : new Profile();
        $weeks = Profile::weeks();
        $workGraph = WorkSchedule::workGraph();
        $gallery = Profile::getGallery();
        $tree = $model->getAllCategories();

        if (Yii::$app->request->isPost) {

         // в контроллере я вижу post, но 


$categories = Yii::$app->request->post('category')
foreach ($categories as $category){

// но когда так делаю то получаю, такой результат: 245, а я выделил три чекбокса 245, 285, 320

            VarDumper::dump(Yii::$app->request->post($categories), 11, 1);
            die;
}
            if ($model->load(Yii::$app->request->post())) {

                $model->gallery = UploadedFile::getInstances($model, 'gallery');
                if ($model->updateProfile()) {
                    Yii::$app->session->setFlash('success', 'Профиль изменен!');
                    return $this->refresh();
                } else {
                    Yii::$app->session->setFlash('error', 'Профиль не изменен!');
                    Yii::error('Ошибка записи. Профиль не изменен!');
                    return $this->refresh();
                }
            }
        }

        return $this->render('profile', [
            'model' => $model,
            'weeks' => $weeks,
            'workGraph' => $workGraph,
            'gallery' => $gallery,
            'tree' => $tree,
        ]);
    }

view
$form = ActiveForm::begin();
foreach ($tree as $cat) {
    echo '<div class="spoiler-title ">' . $cat['title'] . '</div>';
    echo '<div class="spoiler-body">';
    if ($cat['childs'] > 0) {
        foreach ($cat['childs'] as $childs) {
            if (empty($childs['childs'])) {
                echo Html::checkbox('category[]', false, ['value' => $childs['id'], 'label' => $childs['title']]) . '<br>';
            } else {
                echo '<b><br/>' . $childs['title'] . '</b><br/>';
            }
            foreach ($childs['childs'] as $child) {
                echo Html::checkbox('category[]', false, ['value' => $child['id'], 'label' => $child['title']]) . '<br>';
            }
        }
    }
    echo '</div>';
}

echo Html::submitButton('Сохранить', ['class' => 'btn btn-success']);

$form = ActiveForm::end();

var_dump
[
    '_csrf' => 'ZTROVV8ta1IneQstDV4/ZhxWLDg0axoNVmI.Ni1sWQUQRQpmL14aPQ=='
    'category' => [
        0 => '262'
        1 => '264'
        2 => '265'
    ]
]

262, 264, 265 is the category id. Help me save!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2017-03-30
@Uman

Goodnight.
In a loop, foreach().
First you validate, then you use save() with false parameter.
More or less like this

foreach ($values as $value) {
            $value->product_id = $model->id;
            if ($value->validate()) {
                if (!empty($value->value)) {
                    $value->save(false);
                } else {
                    $value->delete();
                }
            }
        }

V
Viktor Umansky, 2017-03-30
@Uman

Thank you for showing the direction, I understood how I had to do

foreach ($category as $k => $category_id) {
                $profileHasCategory = ($profileHasCategory = ProfileHasCategory::find()->where(['user_id' => $user_id])->andWhere(['category_id' => $category_id])->one()) ? $profileHasCategory : new ProfileHasCategory();
                $profileHasCategory->user_id = $user_id;
                $profileHasCategory->category_id = $category_id;
                $profileHasCategory->save(false);
            }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question