Pass parameter to modal window in Yii2 - yii2

I'm using the code below to open a modal window (modal_top10), and now I need to pass a parameter ($manager) to this modal. How do I pass this parameter? Via URL?
<div class="modal fade" id="myModaltop10" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"></div>
<script>
function top10(){
$.ajax({
type:'GET',
url:'index.php?r=/client/base/modal_top10',
success: function(data)
{
$('#myModaltop10').html(data);
$('#myModaltop10').modal();
}
});
}
</script>

first create _modelview file in view folder with following code. Let url of this page is http://example.com/model/show
<?php
echo $data;
?>
note: you must render using renderAjax() method for this view file in controller model
public function actionShow($data)
{
return $this->renderAjax('_modelview', [
'data' => $data,
]);
}
You can render view file in model Where you want as
Modal::begin([
'header' => '<h4>Events</h4>',
'id' => 'events',
'size' => 'model-lg',
]);
echo "<div id='modelContent'></div>";
Modal::end();
then you can create jquery file to show data in model
$(document).ready(function(){
var eventUrl = "http://example.com/model/show";
var data = "data to be sent in this view url for your case $manager";
$.get(eventUrl, {'data': data}, function(data){
$('#events').modal('show')
.find('#modelContent')
.html(data);
});

I could not follow the posts. I did the following:
<?php
Modal::begin([
'header' => "<h4>Top 10</h4>",
'id' => 'top10',
'size' => 'model-lg',
'toggleButton' => [
'tag' => 'a',
'label' => '
<span style="cursor: pointer;">
Veja os associados TOP 10 e cadastre sua visita!
</span>',
]
]);
echo $this->render('_modaltop10', ['manager' => $manager]);
Modal::end();
?>

You can implement this without Ajax.
Modal::begin([
'header' => '<h2>Hello world</h2>',
'toggleButton' => ['label' => 'click me'],
]);
echo $manager;
Modal::end();
Or, for example, use a bootbox (http://bootboxjs.com/).
In controller:
public function actionModalContent(){
$maanager = /*...*/
return $this->asJson($this->renderAjax('modal_content_view', ['manager'=>$manager]));
}

Related

yii2 boostrap 5 and modal

Edit:
I discovered that if i do a clean install, the modal works, and it's after adding hail812/yii2-adminlte3 that the modal system won't work anymore... but i don't find what create this,
original:
little question, does any of you use yii/boostrap5/modal and succeed to render ajax form in a modal ? Because my code used with the older bootstrap won't work.. and i don't find how the new yii/bootstrap5/modal works...
here is my code
<?php
yii\bootstrap5\Modal::begin([
'id' => 'modal',
'size' => 'modal-lg',
//keeps from closing modal with esc key or by clicking out of the modal.
// user must click cancel or X to close
'clientOptions' => ['backdrop' => 'static', 'keyboard' => TRUE]
]);
echo '<div id="modalContent"></div>';
yii\bootstrap5\Modal::end();
?>
<?php
$this->registerJs( <<< EOT_JS_CODE
$(function(){
// changed id to class
$('.modalButton').click(function (e){
e.preventDefault();
$.get($(this).attr('href'), function(data) {
$('#modal').modal('show').find('#modalContent').html(data)
});
document.getElementById('modalHeader').innerHTML = '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button><h4>' + $(this).attr('title') + '</h4>';
return false;
});
});
EOT_JS_CODE
);
?>
the link i use to open the modal:
<?= Html::a(Yii::t('app', 'Ajouter'), ['create-categorie'], ['class' => 'btn btn-success modalButton','title'=>'Nouvelle catégorie']) ?>
And my code in my controller
public function actionCreateCategorie()
{
$model = new Categorie();
if ($model->load(Yii::$app->request->post())) {
$model->created_at = strtotime('now');
$model->updated_at = strtotime('now');
if( $model->save()){
return 'success';
}else{
return 'error';
}
}
return $this->renderAjax('create-categorie', [
'model' => $model,
],false, true);
}
my console with a strange error i don't get

kartik-v/yii2 select2-widget not working with render partial

I am trying to add dynamic drop downs, which will added from javascript on clicking add new button.
view file
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use kartik\select2\Select2Asset;
use yii\helpers\ArrayHelper;
Select2Asset::register($this);
?>
<div class='row'>
<div class='form-group'>
<?=
Select2::widget([
'name' => 'coupons',
'value' => $model->coupon_id,
'data' => ArrayHelper::map($coupons, 'id', 'name'),
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
</div>
controller
public function actionNewCoupon()
{
$coupon = new DealCoupon();
$deal = Yii::$app->request->get('deal');
$order = Yii::$app->request->get('order');
$coupon->deal_id = $deal;
$coupon->order = $order;
$coupon->save();
$coupons = Coupon::find('id','name')->all();
return $this->renderPartial('_form', [
'model' => $coupon,
'coupons' => $coupons
],true, true);
}
js file
.get(BASE_URL + '/coupon/new-coupon', { deal: dealId, order: order }, function(data) {
var dealWidget = newStep.find('.coupon-panel');
$(newStep).find('.coupon-panel').html(data);
});
What I am getting
Any help to resolve this issue is appreciable, as I am totaly lost.
Thanks in advance.
yii\web\Controller::renderPartial() doesn't include registered JS or CSS files. Try using yii\web\Controller::renderAjax() instead. It's similar but it injects registered JS/CSS files into rendered html code.

How can I save data in the database with a form that is loaded via Ajax in Symfony 4?

homepage.html.twig
<a class="load-form" href="{{ path('article_load_form', {slug:page.slug}) }}">Load my beautiful form</a>
<div class="show-form">form will appear here</div>
<script>
$( ".load-form" ).on( "click", function(e) {
e.preventDefault();
var $link = $(e.currentTarget);
$.ajax({method:'POST', url: $link.attr('href')}).done(function(data){
$('.show-form').html(data.output);
});
});
</script>
myController.php
/**
* #Route("/pages/{slug}/heart", name="article_load_form", methods={"POST"})
*/
public function loadForm($slug, Request $request){
$id = 9;
$item = new User();
$item= $this->getDoctrine()->getRepository(User::class)->find($id);
$form = $this->createFormBuilder($item)
->add('username', TextType::class, array('attr' => array('class' => 'form-control')))
->add('email', EmailType::class, array('attr' => array('class' => 'form-control')))
->add('is_active', HiddenType::class)
->add('plainPassword', RepeatedType::class, array('type' => PasswordType::class,'invalid_message' => 'The password fields must match.','options' => array('attr' => array('class' => 'password-field')),'required' => false,'first_options' => array('label' => 'Passwort', 'attr' => array('class' => 'form-control')),'second_options' => array('label' => 'Passwort wiederholen', 'attr' => array('class' => 'form-control')),))
->add('cancel', ButtonType::class, array('label' => 'Abbrechen','attr' => array('class' => 'cancel form-btn btn btn-default pull-right close_sidebar close_h')))
->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
->getForm();
$form->handleRequest($request);
$response = new JsonResponse(
array(
'message' => 'Success',
'output' => $this->renderView('form.html.twig',
array(
'entity' => $item,
'form' => $form->createView(),
))), 200);
return $response;
if($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
}
}
My form is loaded when I click on "Load my beautiful form" with all the data from the database for each field. So this is working fine. BUT when I then change the data inside the form (for example the username from "leo" to "alan") and click the save button, then no data is stored in the database (the username is still "leo").
In the profiler the POST parameters are correct. But no forms were submitted for this request.
The action will return a response before the following block will be reached
if($form->isSubmitted() && $form->isValid()) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->flush();
}
So nothing will be stored in the DB.
then let's see what you are trying to do,
you try to get your beautiful from with ajax and put it to your load-form, so you need at first to use a get method, method:'GET',
after that you need an other ajax method to load your data to the server with post
$('#submit-my-beautiful-form').click(function(e){
e.preventDefault();
var form = $(this).closest('form');
var formData = form.serialize();
alert(formData);
$.ajax({
method:'POST',
url: $link.attr('href'),
data: formData,
success: function(data){
alert(data);
}
});
})
ps: your form data will be serialized and affected to formData variable and then loaded to the server
ps: you need to add an id to your save button :
->add('save', SubmitType::class, array('label' => 'Speichern','attr' => array('id' => 'submit-my-beautiful-form', 'class' => 'form-btn btn btn-info pull-right','style' => 'margin-right:5px')))
ps: dont forget to persist your $item object
$entityManager->persist($item);

Yii2 render view as modal

I want to render view page as a modal for preview
<div>
<?php foreach($softs as $soft) { ?>
<a id="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
<?php
Modal::begin([
'header' => 'Test',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
<?php } ?>
</div>
My controller
public function actionIndex()
{
$query = Documents::find();
$softs = $query->where(['type_id' => 2])->all();
return $this->render('index', [
'softs' => $softs,
]);
}
public function actionView($id)
{
return $this->renderAjax('view', [
'model' => $this->findModel($id),
]);
}
My script
$(function(){
$('#modalButton').click(function (){
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('href'));
});
});
But when I click the link it open a viewpage with no CSS, not a pop-up modal.
Please help me with this. Thank you
You update your code as per below.
<div>
<?php foreach($softs as $soft) { ?>
<!-- updated id to class here -->
<a class="modalButton" href="<?=Url::to(['documents/view', 'id'=>$soft->id]); ?>"><h3><?=$soft->title; ?></h3></a>
<?php } ?>
<!-- We don't need to print modal popup multiple times -->
<?php
Modal::begin([
'header' => 'Test',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'></div>";
Modal::end();
?>
</div>
Update click event.
$(function(){
// changed id to class
$('.modalButton').click(function (){
$.get($(this).attr('href'), function(data) {
$('#modal').modal('show').find('#modalContent').html(data)
});
return false;
});
});

Yii2 Pjax not working

I want to refresh the gridview using Pjax but somehow it is not working. Here is the code:
_search.php
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
$this->registerJs("
$('#btnAjaxSearch').click(function(){
$.ajax({
type: 'get',
data: $('.bank-search form').serializeArray(),
success: function (data) {
$.pjax.reload({container:\"#bank\"});
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('error');
}
});
return false;
});
", \yii\web\View::POS_END, 'bank-search');
?>
<div class="bank-search">
<?php Pjax::begin(['id' => 'bank-form']); ?>
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?= $form->field($model, 'bank_name') ?>
<?= $form->field($model, 'state') ?>
<?= $form->field($model, 'district') ?>
<?= $form->field($model, 'city') ?>
<div class="form-group">
<?= Html::Button('Search', ['class' => 'btn btn-primary','id' => 'btnAjaxSearch']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
</div>
index.php
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\widgets\Pjax;
$this->title = 'Banks';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="bank-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Bank', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(['id' => 'bank']); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
'bank_name',
'state',
'district',
'city',
// 'branch',
['class' => 'yii\grid\ActionColumn'],
],
]); ?>
<?php Pjax::end(); ?>
</div>
Controller
/**
* Lists all Bank models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new BankSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
Simple search is working but Pjax is not. I am new to Yii2 so any help would be appreciated. Thank you.
Thanks Edin. It helped me to solved the problem. Here is what I did. It might help someone facing the same problem.
As Edin mentioned you need to pass the url along with the search parameters to the Pjax in order to refresh the gridview.
Here's my edited code :
$js = <<<JS
// get the form id and set the event
$('#bank-form-id').on('beforeSubmit', function(e) {
var form = $(this);
if(form.find('.has-error').length) {
return false;
}
$.ajax({
url: form.attr('action'),
type: 'post',
data: form.serialize(),
success: function(response) {
var csrf = yii.getCsrfToken();
var bank_name = $('#banksearch-bank_name').val();
var state = $('#banksearch-state').val();
var district = $('#banksearch-district').val();
var city = $('#banksearch-city').val();
var url = form.attr('action')+ '&_csrf='+csrf+'&BankSearch[bank_name]='+bank_name+'&BankSearch[state]='+state+'&BankSearch[district]='+district+'&BankSearch[city]='+city;
$.pjax.reload({url: url, container:'#bank'});
}
});
}).on('submit', function(e){
e.preventDefault();
});
JS;
$this->registerJs($js);
The way Pjax is working is by sending another request with special headers. When pjax request is detected only html required to update container is returned from server. Line
$.pjax.reload({container:\"#bank\"});
will send another request, and inside actionIndex queryParams will be empty.
You can solve this by storing search parameters to session or by specifing pjax url with parameters in query string.
Try following:
var url = urlWithFilters();
$.pjax({url: url, container: '#bank'});
In this case you don't need to create own ajax call, just create url with with filters.