简体   繁体   中英

how to get and display username in another form field when user select name from dropdownlist in yii2?

I want to display the lecturer username in another text input field form when the user selects the lecturer name in the drop-down list above. 这是我的表格

this is my code for drop-down list lecturer name

<?= $form->field($model, 'LecturerName')->dropDownList(
        ArrayHelper::map(User::findAll(['category' => 'lecturer']),'fullname','fullname'),
        ['prompt'=>'Select Lecturer']
        ) ?>

this is my code for lecturer username

<?= $form->field($model, 'LecUsername')->textInput(['maxlength' => true]); ?>

I want to get and display the LecUsername based on the selected drop-down list above. the LecUsername is from the database.

As you are using the dropdown you need to bind the change event for the dropdown to insert the value from the dropdown to the input text. And to make sure that you are inserting the LecUsername for the LecturerName you need to have the LecUsername as the value for the dropdown, means the drop-down data should have the username field as the index, currently you are using the fullname as the index and the value so change the code according to the field name you have for the username, i assume it is username for the example.

ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname')

so your dropdown code will look like

<?= $form->field($model, 'LecturerName')->dropDownList(
        ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname'),
        ['prompt'=>'Select Lecturer']
        ) ?>

then add the below on top of your view file where you have the form

$ddId=Html::getInputId($model, 'LecturerName');
$inputId=Html::getInputId($model, 'LecUsername');

$js = <<< JS
$(document).ready(function(){
    $("#{$ddId}").on('change',function(e){
        $("#{$inputId}").val($(this).val());
    });
});
JS;
 $this->registerJs($js, \yii\web\View::POS_READY);

A better way for dropdowns is to use the library Kartik-v\\select2 and use the event pluginEvents option to specify the event select2:select , your code should look like below in that case.

// Usage with ActiveForm and model
echo $form->field($model, 'LecturerName')->widget(Select2::classname(), [
    'data' => ArrayHelper::map(User::findAll(['category' => 'lecturer']),'username','fullname'),
    'options' => ['placeholder' => 'Select Lecturer'],
    'pluginOptions' => [
        'allowClear' => true
    ],
    'pluginEvents'=>[
        "select2:select" => 'function() { $("#{$ddId}").on('change',function(e){
             $("#{$inputId}").val($(this).val());
         }); }',
    ]
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM