Answer the question
In order to leave comments, you need to log in
How to add required fields dynamically via ajax in yii2?
There are "Real Estate" ads that use different fields for different types of real estate. For example, "plot area" is shown only for houses or cottages, for apartments, garages it is not shown. Now they are simply hidden using jquery (display: none), but I would like to completely remove the fields and load only the necessary ones via ajax.
Where and how should these fields be stored?
Answer the question
In order to leave comments, you need to log in
In short, he divided the entities, as they said. And I load the entire form of the desired property type into the modal window.
<?php Modal::begin([
'size' => 'modal-md',
'header' => '<h4 class="modal-title">Добавление объявления</h4>',
'toggleButton' => [
'tag' => 'button',
'class' => 'btn btn-primary',
'id' => 'modal-button',
'label' => 'Добавить объявление',
]
]); ?>
<div class="form-horizontal">
<div class="form-group">
<label class="col-lg-4 control-label">Тип недвижимости</label>
<div class="col-lg-7">
<select id="rform" class="form-control">
<option value>Выберите тип недвижимости</option>
<option value="0">Квартира</option>
<option value="1">Дом/Часть дома</option>
</select>
<div class="help-block"></div>
</div>
</div>
</div>
<div class="modal-form"></div>
<?php Modal::end(); ?>
<script>var url = '<?= Url::to(['realty/default/showform']); ?>';</script>
<?php
$script = <<< JS
$(document).ready(function(){
$('#rform').on('change', function() {
var val = $('#rform').val();
$.ajax({
type: 'POST',
url: url,
data: {type:val},
beforeSend: function(){
$('.modal-form').html('<div style="text-align:center; margin:10px"><img src="loading.gif" /></div>');
},
success: function(data){
$('.modal-form').html(data);
}
});
});
});
JS;
$this->registerJs($script, View::POS_END);
?>
public function actionShowform()
{
if (Yii::$app->request->isAjax) {
$type = $_POST['type'];
if ($type == 0) {
return $this->renderAjax('/apartment/_form', [
'model' => new Apartment,
]);
} else if ($type == 1) {
return $this->renderAjax('/house/_form', [
'model' => new House,
]);
}
}
}
How do you store data?
Do you use different models for each ad type?
In general, this decision is not at the framework level, but above it.
Form dynamic views depending on the type of objects, you can use reflection, you can simply implement Mapping, in general there are a lot of solutions, choose to your liking.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question