V
V
Vasily2016-11-10 13:18:31
Yii
Vasily, 2016-11-10 13:18:31

How to dynamically load data when selecting an item from a form dropdown list in Yii2?

When filling out the form, I need to implement one of the fields with a drop-down list of users, when you click on the list item, a table with the data of a particular user is loaded and displayed.
I don't know how to use AJAX, I tried to do it through PJAX. It worked out partially. I created a form with a dropdown list and a button, wrapped it in PJAX - when you click on the button, everything works as it should, only the field between the PJAX tags is updated (code below)

<?= date('Y-m-d H:i:s',(new DateTime())->getTimestamp()); ?> //тестовый код для отслеживания обновления областей страницы
    
    <?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('Пробуем', ['class' => 'btn btn-info']) ?>
    
    <?= date('Y-m-d H:i:s',(new DateTime())->getTimestamp()); ?>

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

    //выводимые данные
    <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' => 'Логин',
                    ],
                    [
                    'attribute' => 'building',
                    'label' => 'Корпус',
                    ],
                    [
                    'attribute' => 'room',
                    'label' => 'Кабинет',
                    ],
                ],
           ]); ?>
        </div>
        </div>
    
        <?php endif; ?>
    
    <?php Pjax::end();?>

Okay, but it's not exactly what you need without a button. I rummaged around on the net, found a solution, but when I tried to implement form submission in this way:
<?= $form->field($model, 'field1')
->dropDownList(\yii\helpers\ArrayHelper::map(User::find()->all(), 'id', 'username'), ['onchange' => 'this.form.submit()']); ?>

those. without a button, for some reason the whole page is updated.
What's the best way to do it right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
deleted, 2016-11-11
@parazitl2

1) Поставить ajax клик на пункт меню
2) По событию клика, загрузить, через ajax, данные из yii2 (создай для этого action в контроллере)
3) Разместить данные в html элемент на странице, по завершению запроса

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question