Yii2 dropdown list value not persisted to database
P粉182218860
P粉182218860 2023-09-12 12:44:28
0
1
720

I created a model called AssignForm:

<?php

namespace app\models;

use yii\db\ActiveRecord;

class AssignForm extends ActiveRecord
{
public $username;
public $organ_name;
public $role;

}

Then I added a function called actionAssign in SiteController:

public function actionAssign(){

        $model = new AssignForm();


        if($model->load(Yii::$app->request->post()) && $model->validate()){

            Yii::$app->db->createCommand()
                ->update('users', ['post' => $model->post], "username = '$model->username' ")
             ->execute();

        }


        return $this->render('assign',['model' => $model]);

    }

I also have a view file called assign.php:

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(); ?>
<?php

echo $form->field($model, 'username')->dropDownList(\yii\helpers\ArrayHelper::map(\app\models\Users::find()->all(),'id','username'),
[
        'prompt' => 'Select User!!'
]);
echo $form->field($model, 'role')->dropDownList(['0' => 'employee', '1' => 'responsible'],['prompt'=>'Select Option']);
?>
<div class="form-group">
    <?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>

This displays the correct information, but does not save to the database. But when I use the following code in actionAssign it works fine:

Yii::$app->db->createCommand()
                ->update('users', ['post' => 'ssss'], "username = 'soghra' ")
                ->execute();

But I want to write using database information. How to add to database dynamically?

P粉182218860
P粉182218860

reply all(1)
P粉729518806

There's nothing technical about it... I'm just passing the wrong parameters (username instead of id). Sorry about that.

As follows:

Yii::$app->db->createCommand()
            ->update('users', ['post' => 'ssss'], "id = 'soghra' ")
            ->execute();

Hope it helps you.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template