How to make dynamic loading of data when you select from the drop-down list in Yii2?

When filling out the form I need to implement one of the fields with a dropdown list of users when you click on a list item loads and displays a data table of a specific user.

Aaham can not use tried using PJAX. It turned out partially. Created a form with a dropdown list and a button, wrapped it in PJAX - when you press the button everything works as it should, only updated the box between the tags PJAX (code below)

<?= date('Y-m-d H:i:s',(new DateTime())--->getTimestamp()); ?> //test code for tracking update regions of the page

 <?php Pjax::begin(); ?> 

 <?php $form = ActiveForm::begin(['options' =--> ['data-pjax' => true]]); ?> 

 <?= $form--->field($model, 'field1')
->dropDownList(\yii\helpers\ArrayHelper::map(User::find()->all(), 'id', 'username')); ?> 

 <?php echo Html::submitButton('Try', ['class' =--> 'btn btn-info']) ?>

 <?= date('Y-m-d H:i:s',(new DateTime())--->getTimestamp()); ?>

 <?php ActiveForm::end(); ?>

 <?php if ($model--->field1): ?>

 //output
 <div class="row">
 <div class="col-lg-4">
 <?= DetailView::widget([
 'model' =--> User::findIdentity($model->field1),
 'options' => [
 'class' => 'table table-no-border table-condensed',
],
 'attributes' => [
[
 'attribute' => 'username',
 'label' => 'Login',
],
[
 'attribute' => 'building',
 'label' => 'Body',
],
[
 'attribute' => 'room',
 'label' => 'Account',
],
],
 ]); ?>
</div>
</div>

 <?php endif; ?>

 <?php Pjax::end();?>

Okay, but that's not quite what you need without button. Rummaged in a network found a solution, but when trying to implement form submission thus:
<?= $form--->field($model, 'field1')
->dropDownList(\yii\helpers\ArrayHelper::map(User::find()->all(), 'id', 'username'), ['onchange' => 'this.form.submit()']); ?>

ie, without the buttons, for some reason the whole page is updated.

How best to do the right thing?
July 2nd 19 at 17:55
3 answers
July 2nd 19 at 17:57
Solution
1) Put ajax on click menu item
2) On click event, load, via ajax, the data from yii2 (for this create action in the controller)
3) to Place the data in an html element on the page, at the end of the request
field($model, 'field1')
->dropDownList(\yii\helpers\ArrayHelper::map(User::find()->all(), 'id', 'username'), ['onchange' => '
$.post("ajaxtest?user_id='.'"+$(this).val(), function( data ) {

});'
]); ?>

Could do the first two points, as do the third - do not understand( - margarett commented on July 2nd 19 at 18:00
almost all done, left only inside the functions of callbacka post function to write code which will work after the request. In this case, $(selector).html(data); - dustin.Will94 commented on July 2nd 19 at 18:03
: Thanks! Eventually figured out =) - margarett commented on July 2nd 19 at 18:06
: Glad to help - dustin.Will94 commented on July 2nd 19 at 18:09
July 2nd 19 at 17:59
Solution
You can make a GET request, but given the activeForm, I prefer to do it via POST
Form
<?php $form = ActiveForm::begin([
 'id' =--> 'get_users', //Added ID for tracking in JS
 'action' => \yii\helpers\Url::to(['YOUR ACTION']) //Add the address that it will request, if different from your current location
]); ?> 
<?= $form--->field($model, 'field1')->dropDownList(\yii\helpers\ArrayHelper::map(User::find()->all(), 'id', 'username')); ?> 
<?= Html::submitButton('Try', ['class' =--> 'btn btn-info', 'id'=>'get_users_submit']); ?>
<?php ActiveForm::end(); ?>
<div id="rendered_user"></div>


Controller
public function actionYouraction()
{
 $request = Yii::$app->request;
 if($request->isAjax){ 
 Yii::$app->response->format = Response::FORMAT_JSON; //If the request is Ajax,the answer is JSON-om
 //Then parse the request, write the desired logic, pull up the user model

 return ['content'=>$this->renderAjax('_userdata', [ 'model' => $model])]; //Return a JSON array in the form of views, which pass the user model, or any other desired data
 } 
 }


JS
$(document).on('click' , '#get_users_submit' , function(e) {
e.preventDefault();
 var target= $('#rendered_user'), //In this block we print the received data 
 form = $('#get_users'), //Select our form
 url = form.attr('action'), //find out the url to send
 data = form.serializeArray(); //Serialize the form
$.ajax({
 url: url,
 method: 'POST',
 data: data,
 error: function (response) {
 //If the request failed, then do something
},
 success: function (response) {
 //If the request has passed, then do something
 //Controller return data in the response variable, disassemble it, print what you need
console.log(response);
target.html(response.content);
},
});

});


All from memory, code not tested.
The essence seems to be clear.
Thank You very much!
Figured out yesterday, wrote a response and sent. Today I sent it and then saw Yours :)
From Your answer I learned useful knowledge and I think that again they will take advantage!
-- went to fix it -- - margarett commented on July 2nd 19 at 18:02
July 2nd 19 at 18:01
Solution
Solved the problem as written by Stanislav Kazanin.

The drop-down list when you select which field will be updated on the page with the user data (the id of the list e.g. "useridfield") :
<?php echo $form--->field($model, 'user_id')->widget(Select2::classname(), [ 
 'data' => ArrayHelper::map(User::find()->all(), 'id', 'username'),
 'language' => 'EN',
 'options' => ['placeholder' => 'Select user ...', 'id' => 'useridfield', 'value' => Yii::$app->user->identity->getId(),],
 'pluginOptions' => [
 'allowClear' => true
],
 ])->label('the requester'); ?>

The block itself is on the same page in which the updated user data (id fields, for example, "newtry"):

<div id="newtry">
 <?= $this--->render('/user/_userdataview', [
 'model' => Yii::$app->user->identity,
 ]); ?>
</div>

And this script (decided to leave it at the bottom of the page, then you can put in a separate file) that does all the work:

<?php 
$script = <<< JS

$('#useridfield').change(function(){
$.ajax({
 type: "GET",
 url: "/basic_yii/web/user/showuserdata?user_id="+$(this).val(),
 success: function(data) {
$("#newtry").html(data)
}
})
});

JS;
$this--->registerJs($script);
?>

Script $('#useridfield') is the id of a form field with a dropdown list (specified in options array), $("#newtry") id is a specially separated by div tags field, which is fully updated when you click on the drop-down list, and the address /basic_yii/web/user/showuserdata?user_id= lies action controller:

public function actionShowuserdata($user_id)
{
 $model = \app\models\User::findIdentity($user_id);

 return $this->renderPartial('_userdataview', [
 'model' => $model,
]);
 }


I hope this is useful to someone =)

Find more questions by tags Web DevelopmentYiiPHP