How display kartik\Select2 in modal window use renderAjax - yii2

I use http://demos.krajee.com/widget-details/select2#usage-tags
controller
public function actionTagsForm()
{
$method = Yii::$app->request->isAjax ? 'renderAjax' : 'render';
$model = new UserTagsForm();
return $this->$method('tagsForm', ['model' => $model]);
}
views/layouts/main.php has code modal window
<?php
yii\bootstrap\Modal::begin([
'header' => '<div id="modalHeader"></div>',
'id' => 'modal',
'size' => 'modal-lg',
'options' => [
'tabindex' => false
],
]);
echo "<div id='modalContent'></div>";
yii\bootstrap\Modal::end();
?>
view
$data = [
"red" => "red",
"green" => "green",
"blue" => "blue",
"orange" => "orange",
"white" => "white",
"black" => "black",
"purple" => "purple",
"cyan" => "cyan",
"teal" => "teal"
]; ?>
<div class="image-tags-index">
<?php $form = ActiveForm::begin();?>
<?php echo $form->field($model, 'image_tags')->widget( Select2::classname(),[
'data' => $data,
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
])->label('Tag Multiple');
?>
</div>
error
VM314:2 Uncaught ReferenceError: select2_3f25e3ac is not defined
at eval (eval at globalEval (jquery.js:343), :2:56)
at eval ()
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at jQuery.fn.init. (jquery.js:5525)
at access (jquery.js:3614)
at jQuery.fn.init.html (jquery.js:5492)
at Object. (jquery.js:9436)
at fire (jquery.js:3187)

This problem has been solved in the https://github.com/kartik-v/yii2-widget-select2/issues/211

Related

The upload variable is empty in yii2

i want add uploadFile to: https://github.com/thyseus/yii2-message
i added public $file2 in Message.php in model
and this is my rules in model:
public function rules()
{
return [
[['title'], 'required'],
[['file2'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
[['title', 'message', 'context'], 'string'],
[['title'], 'string', 'max' => 255],
[['to'], IgnoreListValidator::class],
[['to'], 'exist',
'targetClass' => Yii::$app->getModule('message')->userModelClass,
'targetAttribute' => 'id',
'message' => Yii::t('app', 'Recipient has not been found'),
],
[['to'], 'required', 'when' => function ($model)
{
return $model->status != Message::STATUS_SIGNATURE && $model->status != Message::STATUS_DRAFT;
}],
];
}
and this is my view:
<?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
<?php
echo $form->field($model, 'file2')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]);
// With model & without ActiveForm
echo '<label class="control-label">Add Attachments</label>';
echo FileInput::widget([
'model' => $model,
'attribute' => 'file2',
'options' => ['multiple' => true]
]);
?>
and this is my sendMessage Function
$model = new Message();
$model->attributes = $attributes;
var_dump($attributes);
die;
why after upload file my result is this?
array(4) { ["to"]=> array(1) { [0]=> string(2) "65" } ["title"]=> string(3) "asd" ["message"]=> string(30) "asd . " ["file2"]=> string(0) "" }
file2 is empty !
When setting up the form, you need to mention as multipart/form-data. check below example.
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'file2')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>

How to add error messages for DateValidation?

In my model I use DateValidation
['date_birthday', 'date', 'format' => 'd.m.yy', 'min' => '01.01.1900', 'max' => date('d.m.yy'), 'tooSmall'=>'The date is from past. Try another','tooBig' => 'The date is from future. Try another', 'message' => 'Try to input the date'],
In view I call the widget
<?php echo $form->field($modelForm, 'date_birthday')->widget(\kartik\date\DatePicker::classname(), [
'type' => \kartik\date\DatePicker::TYPE_COMPONENT_APPEND,
'pickerButton' => false,
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'autoclose' => true,
'showMeridian' => true,
'startView' => 2,
'minView' => 2,
]
]) ?>
It checks for min and max dates, but show no error message. I think its because of different date formats in model and view. How to fix it?
If you submit form you will see error messages. According to this issue https://github.com/yiisoft/yii2/issues/7745 yii2 have not client-side validations of date
You can enable ajax validation. Add in create and update action before if statement
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
And add use yii\widgets\ActiveForm; on the top of controller class. In your _form.php file enable ajax for whole form
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
]); ?>
, or for the field only
<?php echo $form->field($model, 'date_birthday', ['enableAjaxValidation' => true])->widget(\kartik\date\DatePicker::classname(), [
...
Also, you can add plugin options for limit date with startDate and endDate (https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#startdate)
<?php echo $form->field($model, 'date_birthday', ['enableAjaxValidation' => true])->widget(\kartik\date\DatePicker::classname(), [
'type' => \kartik\date\DatePicker::TYPE_COMPONENT_APPEND,
'pickerButton' => false,
'options' => [
'placeholder' => '',
],
'pluginOptions' => [
'format' => 'dd.mm.yyyy',
'autoclose' => true,
'showMeridian' => true,
'startView' => 2,
'minView' => 2,
'startDate' => '01.01.1900',
'endDate' => date('d.m.Y'),
]
]) ?>

Kartik export widget not export search result Yii2

Fighting form last 3 days not able to find what exactly problem is. When after search I export data it export all data, expected to export search result.Please help!
My Controller
public function actionAdvancesearch()
{
$searchModel = new CandidateSearch();
$model = new Candidate();
$dataProvider1 = $searchModel->search(Yii::$app->request->queryParams);
if(Yii::$app->request->post()){
$postedData=Yii::$app->request->post();
$searchModel = new CandidateSearch();
$dataProvider1 = $searchModel->searchAdvanced();
return $this->render('candidateAdvSearch', ['dataProvider1' => $dataProvider1,
'model' => $model ,
'searchModel' => $searchModel,
'posted'=>"posted",
'postedData'=>$postedData]);
}else{
return $this->render('candidateAdvSearch', ['searchModel' => $searchModel, 'model' => $model, 'dataProvider1' => $dataProvider1]);
}
}
View
Pjax::begin();
if($dataProvider1){
$gridColumns = [
[
'attribute'=>'HRMS_candidateID',
'label'=>'Candidate ID',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateID;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateFirstName',
'label'=>'Candidate FirstName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateFirstName;
},
'format'=>'raw'
],
[
'attribute'=>'HRMS_candidateLastName',
'label'=>'Candidate LastName',
'vAlign'=>'middle',
'width'=>'190px',
'value'=>function ($model, $key, $index, $widget) {
return $model->HRMS_candidateLastName; },
'format'=>'raw'
],
];
$fullExportMenu = ExportMenu::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'target' => ExportMenu::TARGET_POPUP,
'fontAwesome' => true,
'pjaxContainerId' => 'kv-pjax-container',
'dropdownOptions' => [
'label' => 'Full',
'class' => 'btn btn-default',
'itemsBefore' => [
'<li class="dropdown-header">Export All Data</li>',
],
],
]);
// Generate a bootstrap responsive striped table with row highlighted on hover
echo GridView::widget([
'dataProvider' => $dataProvider1,
'columns' => $gridColumns,
'pjax' => true,
'pjaxSettings' => ['options' => ['id' => 'kv-pjax-container']],
'panel' => [
'type' => GridView::TYPE_PRIMARY,
'heading' => '<h3 class="panel-title"><i class="glyphicon glyphicon-book"></i> Candidate Advanced Search</h3>',
],
'toolbar' => [
$fullExportMenu,
],
'striped'=>true,
'hover'=>true,
'responsive'=>true,
'hover'=>true,
'resizableColumns'=>true,
'persistResize'=>false,
'columns' => $gridColumns,
]);
}
Pjax::end();

Put ActiveForm in Gridview Column Yii2

How can put an ActiveForm in a gridview column? The following is the code I made: I tried to render the page such that it includes the active form which I need.
'columns' => [
[ 'format' => 'html',
'value'=> function($data) { return Html::img($data->imageurl) . " <p class='feedback-username'>" . $data->username . "</p>"; },
'contentOptions'=>['style'=>'width: 30px; height: 30px'],
],
[ 'format' => 'raw',
'value' => function($model) { return "<p class='feedback'>". $model->KOMENTAR ."</p><br><p class='feedback-date'>". $model->TANGGAL ."</p><hr><div id='replay-". $model->ID_KOMENTAR."'><ul></ul></div>";},
],
[ 'format' => 'raw',
'contentOptions'=>['style'=>'width: 5px;'],
'value' => function($model) {
if($model->id == Yii::$app->user->identity->id) {
return Html::a('<i class="glyphicon glyphicon-share-alt"></i>',null,['id'=> 'replay-to-'. $model->ID_KOMENTAR ]).' '.
Html::a('<i class="glyphicon glyphicon-pencil"></i>', ['update', 'id' => $model->id]).' '.
Html::a('<i class="glyphicon glyphicon-trash"></i>', ['delete', 'id' => $model->id], ['data' => ['confirm' => 'Do you really want to delete this element?','method' => 'post']]);
}
return Html::a('<i class="glyphicon glyphicon-share-alt"></i>',['feedback', 'id' => $model->id],['id'=> 'replay-to-'. $model->ID_KOMENTAR ]);
},
],
[
'content' => $this->render('feedback_test'),
],
But I got this error:
PHP Warning – yii\base\ErrorException
call_user_func() expects parameter 1 to be a valid callback, function '
<div class="feedback-form">
<p>test</p>
</div>' not found or invalid function name
How do I include the active form in the grid view's column?
Try this.
[
'content' => function($model, $key, $index, $column) {
echo $this->render('feedback_test');
OR
echo $this->render('feedback_test', ['model' => $model]);
},
],
The above answer outputted the form above my grid. I wanted the form in one of my columns for every row of data. I ended up customizing an ActionColumn like this:
[
'class' => 'yii\grid\ActionColumn',
'template' => '{map}',
'contentOptions' => ['class' => 'text-center'],
'buttons' => [
'map' => function ($model) use ($m, $r) {
return $this->render('_form', ['model' => $m, 'req' => $model, 'ref' => $r]);
},
],
'urlCreator' => function ($action, $model) {
if ($action === 'map') {
return $model;
}
},
]

Yii2: Select2, How to set initValueText in Gridview or Tabularform?

I need to set initValueText for Select2, which is in loop, like gridview or Tabularform. but I don't know how to set right value for each.
<?= TabularForm::widget([
'dataProvider' => $dataProvider,
'form' => $form,
'actionColumn' => false,
'checkboxColumn' => false,
'attributeDefaults' => [
'type' => TabularForm::INPUT_RAW,
],
'attributes' => [
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
'initValueText' => 'Selected Text' /// how can I set this in gridview or Tabularform?
],
],
]
]) ?>
Of course this is not working,
'initValueText' => function($model){
retur $model->textValue;
}
Any help would be appreciated.
Into tabularform if you want dynamic initValueText, you can use options closure in this manner:
'test' => [
'type' => Form::INPUT_WIDGET,
'widgetClass' => Select2::className(),
'options' => function($model, $key, $index, $widget) {
$initValueText = empty($model['textValue']) ? '' : $model['textValue'];
return [
'name' => 'test',
'options' => [
'class' => 'test-to-select',
],
'initValueText' => $initValueText,
'pluginOptions' => [
'allowClear' => true,
'minimumResultsForSearch' => 'Infinity',
'ajax' => [
'url' => Url::to(['/test/get-list']),
'dataType' => 'json',
'data' => new JsExpression('function(term,page) {
return {term : term.term};
}'),
'results' => new JsExpression('function(data,page) {
return {results:data.results};
}'),
'cache' => true
]
],
];
}
],
If for example attribute for city, so try this..
$cityDesc = empty($model->city) ? '' : City::findOne($model->city)->description;
'initValueText' => $cityDesc, // set the initial display text
For init value first assign value to $model attribute, if you should not assign so this attribute can take value.
Set the data parameter with the array including the option you want to show. For example for cities:
'options' => [
'data' => \yii\helpers\ArrayHelper::map(\app\models\City::find()->orderBy('id')->asArray()->all(), 'id', 'name'),
]
try to put inside the options instead ouside
'widgetClass' => Select2::className(),
'options' => [
'initValueText' => 'Selected Text'
Don't use isset it return error if more the one filter are use there.
[
'attribute' => 'ad_partner_id',
'value' => function ($model, $key, $index, $widget) {
return $model->partner->name;
},
'filter' => Select2::widget([
'model' => $searchModel,
'initValueText' => !empty($searchModel->ad_partner_id) ? $searchModel->partner->name : "",
'attribute' => 'ad_partner_id',
'options' => ['placeholder' => Yii::t('app', 'Search Partner ...')],
'pluginOptions' => ['allowClear' => true, 'autocomplete' => true,
'ajax' => ['url' => Url::base() . '/partner/get-partners',
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }'),
],
],
]),
],