M
M
Max DangerPro2016-11-25 13:44:44
Yii
Max DangerPro, 2016-11-25 13:44:44

Updating data in a database?

The whole essence of this story is as follows: I display data from the database through GridView. I display checkboxes in the column. And through dropDownList I display the list of categories.

Html::dropDownList('records','id',
            ArrayHelper::map($listData,'id', 'name'),
            ['prompt' => '-- Выбрать категорию --']);

For books selected through the checkbox, you need to change the category.
Damn, I'm stupid)) You also need to pass the id of the book itself, in which the category_id will change.
In $records it turns out:
Array
(
    [0] => 1
    [1] => 3
    [2] => 5
)

And $selection gets the value of the category that needs to be changed. It turned out to be just (int), not an array. I apologize for force majeure
And in the handler I do the following:
There is such a code. $records contains the id of the category that needs to be changed (they are from 1 to N, i.e. this is an array) to $selection which contains the id of the same table (one value here). Everything seems to be simple. I read the documentation, looked at the examples, but I still can’t catch up.
if ($records = Yii::$app->getRequest()->post('records')
                && $selection = Yii::$app->request->post('selection')) {
                foreach($selection as $id){
                    $e = Book::findOne((int)$id);
                    $e->save();
                }
            }

Data comes to both variables, but further
hkar.ru/Mi7k is not updated in any way

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Maxim Fedorov, 2016-11-25
@DangerPro

$records = Yii::$app->getRequest()->post('records');
$selection = Yii::$app->request->post('selection');
if (!is_null($records) && !is_null($selection)) {
    Book::updateAll(['category_id' => $selection], ['id' => $records]);
}

M
Maxim Timofeev, 2016-11-25
@webinar

if
then why are you overthinking? If this is a string
If I understand correctly, then it should be:

$id = $records[$selection];
if($e = Book::findOne($id)){
$e->save();
}

give an example of $_POST

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question