select2 and Pjax not work together in yii2 - widget

when i use pjax in yii2. selec2 widget stops working. while select2 working alone. (not working together)
im using select2 widgets and pjax together. but when submit form with pjax. in new form, select2 not work. (just show loading img). pls help me
what is problem?
I want to use both at the same time.
select2 extention page

in view:
<?php
use yii\helpers\Hrml;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model app\models\Vitrin */
?>
<?php Pjax::begin(); ?>
<?php
if($model->getProductTypeSetting()=='both')
{
echo $this->render('_form', [
'model' => $model,
]);
}
?>
<?php Pjax::end(); ?>
in _form:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post'['data-pjax' => '']); ?>
<?= Html::activeInput('text', $model, 'name', ['class' => $username]) ?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
in controller:
if(Yii::$app->request->post('productType'))
{
$model->productType = $_POST['productType'];
if($model->productType=='physical')
{
return $this->renderAjax('_formProduct', ['products' => $this->getProductName()]);
}
else
throw new \yii\web\HttpException(406, Yii::t('app', 'Your request is invalid.'));
}
in _formProduct:
<!-- BEGIN PAGE CONTENT-->
<?= Html::beginForm(['vitrin/index', 'id' => $id], 'post', ['data-pjax' => '']); ?>
<?php
echo Select2::widget([
'name' => 'name',
'data' => [1 => "First", 2 => "Second", 3 => "Third", 4 => "Fourth", 5 => "Fifth"],
'options' => [
'placeholder' => 'Select a type ...',
],
]);
?>
<?= Html::submitButton('Submit', ['class' => 'submit']) ?>
<?= Html::endForm() ?>
<!-- END PAGE CONTENT-->
and AppAssets class:
class AppAsset extends AssetBundle
{
public $basePath = '#webroot/themes/backend';
public $baseUrl = '#web/themes/backend/assets_t';
public $css = [
'bootstrap-rtl/css/bootstrap-rtl.min.css',
'bootstrap-rtl/css/bootstrap-responsive-rtl.min.css',
'font-awesome/css/font-awesome.css',
'fancybox/source/jquery.fancybox.css',
'uniform/css/uniform.default.css',
];
public $js = [
'bootstrap-rtl/js/bootstrap.min.js',
'js/jquery.blockui.js',
'uniform/jquery.uniform.min.js',
];
when submit _form with pjax. in _formProduct, select2 not work. (just show loading img).
Generally, when I use Pjax, other Js codes are deactivated.

In your view header:
use kartik\select2\Select2Asset;
Select2Asset::register($this);
Also make sure you have the latest Select2 widget.

Related

Modal Form not work in Yii2 with AdminLTE

I built a web app using Yii2 with adminLTE theme. i'm trying to make modal form in my web app, I've tried in Yii2 without adminLTE it work fine like this:
I did the same way in Yii2 with adminLTE it failed, when I clicked the button, it didn't do anything, and I tried to do inspectElement and I got this:
This is my view in index.php:
<?php
use yii\helpers\Html;
use kartik\detail\DetailView;
use kartik\grid\GridView;
use yii\helpers\Url;
use yii\bootstrap\Modal;
/* #var $this yii\web\View */
/* #var $modelTrip backend\models\TripsSchedule */
\yii\web\YiiAsset::register($this);
?>
<p>
<?= Html::button('Add Schedule', ['value' => Url::to('/intra/admin/bus-passengers/create'), 'class' => 'btn btn-success', 'id' => 'modalButton']) ?>
</p>
<?php
Modal::begin([
'header' => '<h4>Add Passenger</h4>',
'id' => 'modal',
'size' => 'modal-lg',
]);
echo "<div id='modalContent'><div>";
Modal::end();
?>
<div>
<?=
DetailView::widget([
'model' => $modelTrip,
'id' => $modelTrip->tripScheduleId,
'responsive' => true,
'enableEditMode' => false,
'condensed' => true,
'hover' => true,
'mode' => DetailView::MODE_VIEW,
'mainTemplate' => '{detail}',
'attributes' => [
[
'attribute' => 'departureTime',
'label' => 'Departure Time',
'value' => function ($form, $widget) {
$model = $widget->model;
return date('H:i', strtotime($model->departureTime)) . ' WIB';
},
],
],
])
?>
</div>
This is code in controller:
public function actionCreate()
{
$model = new BusPassengers();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->busPassengerId]);
}
return $this->renderAjax('create', [
'model' => $model,
]);
}
You can see, it didn't render anything. Do I need add another additional code because I'm using adminLTE?
Update
Here is the js:
$(function () {
$('#modalButton').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
Update
Here is the view source and console screenshot
This line is not needed if you already have a layout file, so please remove this
\yii\web\YiiAsset::register($this);
also please make sure jquery file loaded before your js code else it will not work since bootstrap modal is depend on jQuery (please check your console).
Or at the end, your can add js code as Yii way:
<?php
$script = <<< JS
$('#modalButton').click(function () {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
JS;
$this->registerJs($script);
?>
Let me know if it work or please post screenshot of viewSource and console.
Thank you
Update
Try replace these code block and it will work:
1. JS
<script type="text/javascript">
function showModal() {
$('#passenger_modal').modal('show');
$('#passenger_modal_content').load("<?=Yii::getAlias('#web')?>/intra/admin/bus-passengers/create");
}
</script>
2. BUTTON
<p>
<?= Html::button('Add Schedule', ['class' => 'btn btn-success', 'onClick'=>'showModal()']) ?>
</p>
3. MODAL BLOCK
<?php
Modal::begin([
'header' => '<h4>Add Passenger</h4>',
'id' => 'passenger_modal',
'size' => 'modal-lg',
]);
echo '<div id="passenger_modal_content"><div>';
Modal::end();
?>
I just change the id's of blocks but that is not matter at all.
this updated version worked for me problem was my layout footer was hidden and being shown with modal body with this question solution
Yii2 and adminlte : 2.4.13
<?php
Modal::begin([
'header' => '<h4><i class="fa fa-book" style="padding-right:5px"></i>' .
$model->name
. '</h3>',
'id' => 'modal',
'size' => 'modal-lg',
]);
?>
<?= "<div id='modalContent'>" ?>
<?php
$form = ActiveForm::begin(); ?>
<div class="box box-info">
<div class="box-body">
<div class="form-group">
<?= $form->field($chapter, 'name')->textInput() ?>
</div>
<div class="form-group">
<?= $form->field($chapter, 'book_id')->hiddenInput(['value' => $model->id])->label(false); ?>
</div>
<div class="form-group">
<?= $form->field($chapter, 'description')->textarea(['rows' => '6']) ?>
</div>
</div>
<div class="box-footer">
<?= Html::a('Cancel', ['index'], ['class' => 'btn btn-default']) ?>
<?= Html::submitButton('Save', ['class' => 'btn btn-info pull-right']) ?>
</div>
</div>
<?php ActiveForm::end();
Modal::end();
?>
" ?>
<script>
$(function() {
$('#modalButton').click(function() {
$('#modal').modal('show')
.find('#modalContent')
.load($(this).attr('value'));
});
});
</script>

Yii2 Basic call action from different controller

Is it possible to call action from a controller in different view ?
example
I have 2 controllers : Post and Blog , so I want to call actionCreate from post but inside blog view not in post view. I have 2 views and 2 controllers :
view :
1. views/blog/view
2. views/post/view
controller
1. controllers/blogController.php
2. controllers/postController.php
controllers/PostController.php :
public function actionCreate()
{
$model_Post = new Post();
if ($model_Post->load(Yii::$app->request->post()) && $model_Post->save()) {
return $this->redirect(['view', 'id' => $model_Post->Post_id]);
} else {
return $this->render('/blog/view', [
'model_Post' => $model_Post,
]);
}
}
views/blog/view.php
<?php
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Likectt */
$this->title = $model->Blog_id;
?>
<div class="blog-view">
<h1><?= Html::encode($this->title) ?></h1>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Blog_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Blog_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'Blog_id',
'Blog_title',
'Blog_text',
'User_id',
'Category_id',
],
]) ?>
<?= Yii::$app->runAction('PostController/actionCreate', ['model_Post'=>$model_Post]);?>
</div>
Yes you can do that :
In you blog view :
Yii::$app->runAction('postController/actionCreate', ['param1'=>'value1', 'param2'=>'value2']);

Yii2 Basic sql query in view

I'm trying to get the user profile image of the author of the content inside the view , my view is channel I created but I get this error on my view
Undefined variable: queryAvatar
on my view I did
//Yii2 View code
use yii\helpers\Html;
use yii\widgets\DetailView;
/* #var $this yii\web\View */
/* #var $model app\models\Channel */
$this->title = $model->Channel_name;
?>
<div class="channel-view">
<h1><?= Html::encode($this->title) ?></h1>
<div><?php echo $queryAvatar; ?></div> // THE LINE I ADD
<?php if($model->uid == Yii::$app->user->id):?>
<p>
<?= Html::a('Update', ['update', 'id' => $model->Channel_id], ['class' => 'btn btn-primary']) ?>
<?= Html::a('Delete', ['delete', 'id' => $model->Channel_id], [
'class' => 'btn btn-danger',
'data' => [
'confirm' => 'Are you sure you want to delete this item?',
'method' => 'post',
],
]) ?>
</p>
<?php endif;?>
</div>
and on my controller I created this function
//function on my controller
public function actionChannel($id)
{
$cchannel = new Channel();
$queryAvatar = (new \yii\db\Query())
->select(['uavatar'])
->from('userlogin')
->where(['uid' => $cchannel->uid])
->All();
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar '=> $queryAvatar ,
]);
}
in your controller you define an empty model so your $cchannel->uid is empty.
You must define first your model like this
public function actionChannel($id)
{
$cchannel = $this->findModel($id);
$queryAvatar = (new \yii\db\Query())
->select(['uavatar'])
->from('userlogin')
->where(['uid' => $cchannel->uid])
->All();
return $this->render('channel', [
'model' => $cchannel ,
'queryAvatar '=> $queryAvatar ,
]);
}
The problem can be caused by space when you created array of variable before giving to view.
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar '=> $queryAvatar ,
]);
remove space from 'queryAvatar '
Like this:
return $this->render('channel', [
'model' => $this->findModel($id),
'queryAvatar'=> $queryAvatar ,
]);
Another problem can be caused by partial view in side view. For example when you call view:channel from controller inside it may be you view called like this.
<?=$this->render('your_view')?>
So, you should pass your variable to this view also like this.
<?=$this->render('your_view',['queryAvatar'=>$queryAvatar])?>
And finally you cannot echo the varable $queryAvatar beacuse it is array of objects. Therefore use the function print_r();
Like this.
<div><?php print_r($queryAvatar); ?></div> // THE LINE I ADD

Yii2 update a record based on form in a view file

I tried to update one field of record based on value in a form. The form are placed within a modal in a view file.
view
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
But I have no idea how to pass those value to my controller so it can update whatever the user have input and submitted.
Controller
public function actionPay($id)
{
$model = Purchase::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->pcstatus = 'Paid';
$model->pcpaydate = date('Y-m-d H:i:s');
$model->save();
return $this->redirect(['view', 'id' => $model->pcid]);
}
}
I'm new to Yii framework. Any help is much appreciated.
EDIT
The only thing I want to do is to update only this field (current record/view) into database instead of update the whole field.
You must set action in your form with id, it will work
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin([
'action' => ['controller/pay','id'=>$id],
]); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
I think this is the problem regarding csrf validation, just make sure in your config about enableCsrfValidation :
just put this function in your controller
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
Let me know please.

Yii2 upload image from modal issue

I'm using yii2 bootstrap modal for uploading images, the issue is I need to double click on Create button then form submit works otherwise it don't work on single click.
On double click image is uploading and form data also saved to database.
Is this issue with my code?
Here is code:
//Form
<?php Pjax::begin(['id' => 'banner-form']) ?>
<?php $form = ActiveForm::begin([
'id' => 'banner-form',
'options' => [
'data-pjax' => true,
'enctype' => 'multipart/form-data'
]
]);
?>
<?= $form->field($model, 'title')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'banner')
->fileInput([
"accept"=>"image/*"
])
?>
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Pjax::end(); ?>
//Model
[['banner'], 'file', 'skipOnEmpty' => false,
'extensions' => ['jpg', 'jpeg', 'png', 'gif']
]
//index.php
<p>
<?= Html::a(Yii::t('app', 'Create Banner'), null, ['class' => 'btn btn-success', 'id'=>'createBannerButton',
'value'=>Url::to(['/banner/create'])]) ?>
</p>
<?php Pjax::begin(['id' => 'banner-index']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
....
]); ?>
<?php Pjax::end(); ?>
//Controller
use yii\web\UploadedFile;
class BannerController extends Controller
{
...
public function actionCreate()
{
$model = new Banner();
if ($model->load(Yii::$app->request->post())){
$file = UploadedFile::getInstance($model, 'banner');
if (!empty($file))
$model->banner = $file;
if($model->save()){
if (!empty($file))
$file->saveAs( Yii::getAlias('#root') .'/uploads/' . $file);
return $this->redirect(['view', 'id' => $model->id]);
}
}
else if (Yii::$app->request->isAjax) {
return $this->renderAjax('create', [
'model' => $model,
]);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}
...
}
//layouts/main.php
<?php
Modal::begin([
'header' => '',
'id' => 'modal',
'size' => 'modal-medium', //medium
'clientOptions' => ['backdrop' => 'static', 'keyboard' => false]
]);
echo "<div id='modalContentBackend'>
<div class='col-lg'>
<img src='/images/loading.gif' width='280' height='210' alt='loading...'>
</div>
</di>";
Modal::end();
?>
<?php $this->endBody() ?>
//backend/web/js/custom.js
$(function(){
$("#createBannerButton").click(function(){
$("#modal").modal('show')
.find('#modalContentBackend')
.load($(this).attr('value'));
});
});
//backend/assets/AppAsset
class AppAsset extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'css/site.css',
];
public $js = [
'js/custom.js'
];
public $depends = [
'yii\web\YiiAsset',
'yii\bootstrap\BootstrapAsset',
];
}
I got the issue, I'm including Pjax::begin() in index.php and _form.php, I have removed Pjax::begin() from _form.php and now it is working fine.