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?
There's nothing technical about it... I'm just passing the wrong parameters (
username
instead ofid
). Sorry about that.As follows:
Hope it helps you.