Home  >  Q&A  >  body text

Yii2 dropdown list value not persisted to database

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粉182218860P粉182218860404 days ago665

reply all(1)I'll reply

  • P粉729518806

    P粉7295188062023-09-13 00:39:15

    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.

    reply
    0
  • Cancelreply