hi all i'm a noob of yii and i'm trying to get the kartiks to work, but I can't get them to load the dependency.I'm trying to make the kartik work but I can't get it to load the dependency, if I see the calls that are made through yii's built-in debugging the scream that is present in the 'URL' parameter is not really computed, I've also tried to write it fixed but it's not really thought.
If I do a simple echo, however, it comes back correct.
<?=$form->field($model, 'name')->
widget(Select2::classname(), ['data' => $listdataA,
'id' => 'invoice-name',
'options' => ['placeholder' => 'Seleziona anagrafica ...', 'id' => 'lvl-0',],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
'select2:select' => new JsExpression("function (e) {
var id=e.params.data.id;
$.get('index.php?r=invoice/get-location-address', {id: id}, function(data) {
if (data !== null) {
document.getElementById('piva').value=data.PIVA;
document.getElementById('indi').value=data.Indirizzo;
} else {
//if data wasn't found the alert.
alert('We\'re sorry but we couldn\'t load the the location data!');
}
});
}")]
]);
?>
<?= $form->field($model, 'attn')->textInput(['maxlength' => true, 'placeholder' => 'ATTN', 'id' => 'piva'])->label(false) ?>
<?= $form->field($model, 'address')->textarea(['rows' => 6, 'placeholder' => 'Address', 'id' => 'indi'])->label(false) ?>
<?php
echo $form->field($model, 'cd_contact')->widget(DepDrop::classname(), [
'options' => ['placeholder' => 'Select ...'],
'type' => DepDrop::TYPE_SELECT2,
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => [Html::getInputId($model, 'name')], //['lvl-0'],
'url' => Url::to(['/contact/list']),
'loadingText' => 'caricamento dati ...',
]
]);
?>
in the controller
public function actionList() {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = [];
if (isset($_POST['depdrop_parents'])) {
$id = end($_POST['depdrop_parents']);
$list = Contact::find()->andWhere(['id_ana_ref' => $id])->asArray()->all();
var_dump($list);
$selected = null;
if ($id != null && count($list) > 0) {
$selected = '';
foreach ($list as $i => $account) {
$out[] = ['id' => $account['id_contact'], 'name' => $account['Name']];
if ($i == 0) {
$selected = $account['id_contact'];
}
}
// Shows how you can preselect a value
return ['output' => $out, 'selected' => $selected];
}
}
solved if you put any java on kartick they avoid standard code
solution
<?=
$form->field($model, 'name')->
widget(Select2::classname(), ['data' => $listdataA,
'id' => 'invoice-name',
'options' => ['placeholder' => 'Seleziona anagrafica ...' ,'id' => 'lvl-0',],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'attn')->textInput(['maxlength' => true, 'placeholder' => 'ATTN','onclick'=>'magsearch()', 'id' => 'piva'])->label(false) ?>
<?= $form->field($model, 'address')->textarea(['rows' => 6, 'placeholder' => 'Address', 'id' => 'indi'])->label(false) ?>
<?php
// $url = \yii\helpers\Url::to(['index.php?r=contact/list']);
echo $form->field($model, 'cd_contact')->widget(DepDrop::classname(), [
'data' => $datac,
'options' => ['placeholder' => 'carico ...'],
'type' => DepDrop::TYPE_SELECT2,
'select2Options' => ['pluginOptions' => ['allowClear' => true]],
'pluginOptions' => [
'depends' => ['lvl-0'],
'url' => Url::to(['/contact/list']),
// 'params' => ['lvl-0'],
'loadingText' => 'caricamento dati ...',
]
]);
?>
Related
I made a tabular input where I would enter several records at once into one table in the database.
I use this extension: https://github.com/unclead/yii2-multiple-input/wiki/Usage#tabular-input
From this extension, I combine it with dependent dropdown.
Here is the code.
public function actionCreateMulti() {
$request = Yii::$app->request;
$models = [new MaterialLocations()];
if ($request->isAjax) {
/**
* Process for ajax request
*/
Yii::$app->response->format = Response::FORMAT_JSON;
if ($request->isGet) {
return [
'title' => "Create new MaterialLocations",
'content' => $this->renderAjax('_form_create_multi', [
'models' => $models,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Order', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else if ($eglData = $request->post('MaterialLocations', [])) {
foreach (array_keys($eglData) as $index) {
$models[$index] = new MaterialLocations();
}
if (Model::loadMultiple($models, $request->post()) && ActiveForm::validateMultiple($models)) { // if failed
return [
'title' => "Create new MaterialLocations",
'content' => $this->renderAjax('_form_create_multi', [
'models' => $models,
]),
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Order', ['class' => 'btn btn-primary', 'type' => "submit"])
];
} else { // success
foreach ($models as $single) {
$single->save(false);
}
return [
'forceReload' => '#crud-datatable-pjax',
'title' => "Create new MaterialLocations",
'content' => '<span class="text-success">Create MaterialLocations success</span>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::a('Create More', ['create'], ['class' => 'btn btn-primary', 'role' => 'modal-remote'])
];
}
} else {
return [
'title' => "Create new MaterialLocations",
'content' => '<pre>' . VarDumper::dumpAsString($request->post()) . '</pre>',
'footer' => Html::button('Close', ['class' => 'btn btn-default pull-left', 'data-dismiss' => "modal"]) .
Html::button('Order', ['class' => 'btn btn-primary', 'type' => "submit"])
];
}
} else {
/**
* Process for non-ajax request
*/
new ForbiddenHttpException(); // just for test
}
}
And the following is a view of the tabular input.
<?php $form = ActiveForm::begin(); ?>
<?php try {
echo TabularInput::widget([
'id' => 'some-id',
'models' => $models,
'cloneButton' => true,
'addButtonPosition' => MultipleInput::POS_FOOTER,
'sortable' => true,
'columns' => [
[
'name' => 'cupboard_id',
'title' => $models[0]->getAttributeLabel('cupboard_id'),
'enableError' => true,
'type' => Select2::className(),
'options' => [
'data' => $cupBoards,
'options' => [
'prompt' => '== Choose a vendor ==',
'onChange' => $jsOnChange, // this is handle onChange to find list row
'class' => 'form-control cupboard-id',
]
],
],
[
'name' => 'row',
'title' => $models[0]->getAttributeLabel('row'),
'type' => 'dropDownList',
'items' => [],
'value' => function ($data) {
return $data->row;
},
'options' => [
'class' => 'form-control row-cupboard',
],
'columnOptions' => [
'style' => 'width: 100px;',
]
],
],
]);
} catch (Exception $e) {
echo $e->getMessage();
} ?>
<?php ActiveForm::end(); ?>
As you can see, the first input column is: 'cupboard_id',
If there is onChange, it will generate data for the 'row' column.
<?php
$urlOnChangeCupboard = Url::toRoute(['cupboards/find-row-column-available']);
$jsOnChange = <<<JS
var cupboard = jQuery(this);
var row = cupboard.closest('tr');
var rowCupboard = row.find('.row-cupboard');
var columnCupboard = row.find('.column-cupboard');
jQuery.post('$urlOnChangeCupboard', { id : cupboard.val() }, function(response){
rowCupboard.find('option').remove().end();
columnCupboard.find('option').remove().end();
jQuery.each(response.data.rows, function(index, value){
rowCupboard.append('<option value=' + value + '>' + value + '</option>');
});
});
JS;
?>
<?php
function callBack($cupboardID) {
$data = Cupboards::find()->where(['id' => $cupboardID])->one();
$rowsRaw = range($data->rows_start, $data->rows_amount);
$rows = array_combine($rowsRaw, $rowsRaw);
return $rows;
}
?>
The problem is, when POST (Submit) the data, and then it is validated and there are still errors,
data from the column row should still be based on the cupboard selection.
At this time, after posting, the data from 'row' is empty
Please help.
Fixed with columnOptions closure
[
'name' => 'row',
'title' => $models[0]->getAttributeLabel('row'),
'type' => 'dropDownList',
'items' => function ($model) {
$data = [];
if (isset($model->row)) {
$cupBoards = Cupboards::find()->where(['id' => $model->cupboard_id])->one();
$rowsRaw = range($cupBoards->rows_start, $cupBoards->rows_amount);
$data = array_combine($rowsRaw, $rowsRaw);
}
return $data;
},
'value' => function ($data) {
return $data->row;
},
'options' => [
'class' => 'form-control row-cupboard',
],
'columnOptions' => [
'style' => 'width: 100px;',
]
],
i have gridview table like this :
i want to merge store 1(example) with 4 row detail information. is it possible to do it with?
i have a code in gridview :
<?php Pjax::begin(['id' => 'pjax_filesetting','timeout'=>false]) ?>
<?php
$this->registerJs(
"
$('.btneditfile').click(function(){
var hqid = $(this).attr('data-hqid');
var storeid = $(this).attr('data-storeid');
var filename = $(this).attr('data-filename');
location.href = '/pos/editfilesetting?hqid='+hqid+'&storeid='+storeid+'&filename='+filename;
return false;
});
");
?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'options' => ['class' => 'grid-view active-table'],
'columns' =>
[
['class' => 'yii\grid\SerialColumn'],
[
'label' => 'Store Name',
'attribute' => 'store_name',
'encodeLabel' => false,
],
[
'label' => 'Filename',
'attribute' => 'filename',
'encodeLabel' => false,
],
[
'label' => 'Datecheck',
'attribute' => 'datecheck',
'encodeLabel' => false,
'value' => function($model){
$datecheck = $model["datecheck"];
if($datecheck)
{
return $model["datecheck"] = "Check";
}
else
{
return $model["datecheck"] = "Not Check";
}
}
],
[
'label' => 'Timecheck',
'attribute' => 'timecheck',
'encodeLabel' => false,
'value' => function($model){
$timecheck = $model["timecheck"];
if($timecheck)
{
return $model["timecheck"] = "Check";
}
else
{
return $model["timecheck"] = "Not Check";
}
}
],
[
'label' => 'Maintenance code',
'attribute' => 'maincode',
'encodeLabel' => false,
],
[
'label' => 'Final Filename',
'attribute' => 'usedfilename',
'encodeLabel' => false,
],
[
'class' => 'yii\grid\ActionColumn',
'template' => '<div align="center">{update} {delete}</div>',
'buttons' => [
'update' => function ($url, $model) use ($controller) {
return Html::button(
'<span class="glyphicon glyphicon-pencil"></span>',
[
'class' => 'btn btn-primary btn-xs btneditfile',
'title' => Yii::t( $controller->transmodule, 'Edit' ),
'style' => ['padding-top' => '5px', 'padding-bottom' => '5px'],
'id' => 'editfile',
'data-storeid' => $model['id'],
'data-hqid' => $model['cmshqid'],
'data-filename' => $model['filename']
]
);
},
'delete' => function ($url, $model)use ($controller){
return Html::button(
'<span class="glyphicon glyphicon-trash"></span>',
[
'class' => 'btn btn-danger btn-xs btndeletefile',
'title' => Yii::t( $controller->transmodule, 'Delete' ),
'style' => ['padding-top' => '5px', 'padding-bottom' => '5px'],
'data-storeid' => $model['id'],
'data-hqid' => $model['cmshqid'],
'data-filename' => $model['filename']
]
);
},
],
]
],
]) ?>
<?php Pjax::end() ?>
what must i do to merge it?
what i need is if the store name is same, merge it column .
Is the store and other details in one table or separate table? If it is in separate tables, the $dataProvider should query from the store table. In the store model create a hasMany relation to the other table which contain the details. So in the view, in the gridview column function you can loop through those values and display it in the same row.
I have load select2 data like this :
$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name');
echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'data' => $data,
'model' => $model,
'language' => 'en',
'options' => ['placeholder' => Yii::t('modules','Pilih Kelompok')],
'pluginOptions' => [
'allowClear' => true,
'multiple' => true,
],
])->label('Kelompok');
$data variable returning result :
Array
(
[1] => Tanpa Kategori
[3] => Bisnis
[4] => Kawan
[5] => Bisnis Kerang
[6] => Bisnis Selang
[99] => Keluarga
)
and select2 working properly, but I can't show selected value or initial value. is I've missed something ?
you add tags property in pluginOptions for multiple selection like....
$data = ArrayHelper::map(ContactGroups::find()->where(['group_status'=>'ACTIVE'])->asArray()->all(),'group_id', 'group_name');
foreach($data as $d)
$row[]=$d;
echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'language' => 'en',
'name' => 'group_id[]',
'options' => ['placeholder' => ''],
'pluginOptions' => [
'tags' => $row,
'allowClear' => true,
'multiple' => true
],
])->label('Kelompok');
You show Demo
Try using like this.. At the time of updating we need to take already selected values in 1 variable and all values in 1 variable.. and send this to select2.
$query = NewsTags::find()->where(['news_id' => $model->id])->all();
$services = array();
$services_id_list = array();
foreach ($query as $ds) {
$tag_id = $ds->tag_id;
$tag_name = Tags::findOne($tag_id)->tag_name;
$services[$ds->tag_id] = $tag_name;
array_push($services_id_list, $ds->tag_id);
}
$data= ArrayHelper::map(Tags::find()->where([])->all(),'id','tag_name');
echo Select2::widget([
'name' => 'NewsTags[tag_id][]',
'id' => 'newstags-tag_id',
'value' => $services_id_list,
'data' => $data,
'maintainOrder' => true,
'options' => [
'placeholder' => 'Select a Service ...',
'multiple' => true
],
'pluginOptions' => [
'tags' => true,
'maximumInputLength' => 10
],
]);
here NewsTags[tag_id][] is the model and its column. we are not directly calling $model->attribute here
Having a look at the code of kartik\base\InputWidget line 190 :
if ($this->hasModel()) {
$this->name = !isset($this->options['name']) ? Html::getInputName($this->model, $this->attribute) : $this->options['name'];
$this->value = !isset($this->options['value'])? Html::getAttributeValue($this->model, $this->attribute) : $this->options['value'];
}
I've found out that, when loading data with AJAX, initial multiple values should be set in options[value] like this:
<?= $form->field($model, $attribute)->widget(Select2::className(), [
'initValueText' => $initText, // array of text to show in the tag for the selected items
'options' => [
'placeholder' => 'Any text you want ...',
'multiple' => true,
'class' => 'form-control',
'value' => $initIds, // array of Id of the selected items
],
whereas setting value next to initValueText leads to an array_combine error
I'm using wbraganca yii2-dynamicform and kartik yii2-widget-fileinput. The form works fine but when I'm trying the getinstance for upload the images always is null.
This is my controller.
public function addMultipleImage($model){
$modelsOptionValue = Model::createMultiple(OptionValue::classname());
Model::loadMultiple($modelsOptionValue, Yii::$app->request->post());
foreach ($modelsOptionValue as $index => $modelOptionValue) {
$modelOptionValue->sort_order = $index;
$file[$index]= UploadedFile::getInstanceByName("OptionValue[".$index."][upload_image]");
var_dump($file[$index]);
if($file[$index]){
$ext = end((explode(".", $file[$index]->name)));
// generate a unique file name
$modelOptionValue->img= Yii::$app->security->generateRandomString().".{$ext}";
$path[$index]= Yii::getAlias ('#web') ."/img/". $modelOptionValue->img;
}else{
return false;
}
}
View form
//_form.php
<?php $form = ActiveForm::begin( [
'enableClientValidation' => false,
'enableAjaxValidation' => true,
'validateOnChange' => true,
'validateOnBlur' => false,
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]);
?>
//_form_add_image.php
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper',
'widgetBody' => '.form-options-body',
'widgetItem' => '.form-options-item',
'min' => 1,
'insertButton' => '.add-item',
'deleteButton' => '.delete-item',
'model' => $modelsOptionValue[0],
'formId' => 'dynamic-form',
'formFields' => [
'upload_image'
],
]); ?>
<?= $form->field($modelOptionValue, "[{$index}]upload_image")->label(false)->widget(FileInput::classname(), [
'options' => [
'multiple' => false,
'accept' => 'image/*',
'class' => 'optionvalue-img'
],
'pluginOptions' => [
'previewFileType' => 'image',
'showCaption' => false,
'showUpload' => false,
'browseClass' => 'btn btn-default btn-sm',
'browseLabel' => ' Seleccionar Imagen',
'browseIcon' => '<i class="glyphicon glyphicon-picture"></i>',
'removeClass' => 'btn btn-danger btn-sm',
'removeLabel' => ' Borrar',
'removeIcon' => '<i class="fa fa-trash"></i>',
'previewSettings' => [
'image' => ['width' => '138px', 'height' => 'auto']
],
'initialPreview' => $initialPreview,
'layoutTemplates' => ['footer' => '']
]
]) ?>
and my model
public $upload_image;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'option_value';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['upload_image'], 'file', 'extensions' => 'png, jpg', 'skipOnEmpty' => true],
[['id_montacarga', 'sort_order'], 'integer']
];
}
screenshot of yii2 log. updated
inspect element screenshot
Thanks!!!
Add 'enctype' => 'multipart/form-data' in ActiveForm.
<?php $form = ActiveForm::begin([
'options' => [
'enctype' => 'multipart/form-data',
'id' => 'dynamic-form'
]
]); ?>
Set Ajax Validation to false if you don't want ajax validation.
Reference
In Yii2 I want one of my input field to be autocomplete when user starts to type.Below is my code which uses Jui Autocomplete.
<?php
$items= ArrayHelper::map(Company::find()->all(), 'c_id', 'name');
echo AutoComplete::widget([
'model' => $model,
'attribute' => 'company',
'clientOptions' => [
'source' => $items,
],
]);?>
This is not working.When i printed my array, i got like
Array ( [1] => abc [2] => xyz [4] => pqr )
I got it working when i manually set like
$items=['abc','xyz','pqr'];
The reason may be my c_id's are not ordered?But i want to get the c_id value to be submitted!Any idea how to fix this?
This can be solved with the help of a hidden field input.Hope this will help somebody!
<?php
use yii\web\JsExpression;
$data = Company::find()
->select(['name as value', 'name as label','c_id as id'])
->asArray()
->all();
echo AutoComplete::widget([
'name' => 'Company',
'id' => 'ddd',
'clientOptions' => [
'source' => $data,
'autoFill'=>true,
'minLength'=>'4',
'select' => new JsExpression("function( event, ui ) {
$('#user-company').val(ui.item.id);
}")
],
]);
?>
<?= Html::activeHiddenInput($model, 'company')?>
Autocomplete just helps you fill the field with required value.
If you need to submit c_id look to dropdownList or Select2 plugin.
Check this http://demos.krajee.com/widget-details/select2 yii2 widget for ideas.
Here example code:
<?php
use kartik\widgets\Select2;
use app\models\Modelname;
$model = new Modelname;
$data = ['qwe1'=>'color1','key2'=>'color3']
?>
<?= Html::beginForm() ?>
<?= Select2::widget([
'model' => $model,
'attribute' => 'color',
'data' => array_merge(["" => ""], $data),
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= Html::submitButton('Submit', ['class' => 'btn btn-primary']) ?>
<?= Html::endForm() ?>
It also supports ajax loaded data: http://demos.krajee.com/widget-details/select2#ajax
I wanted to use the Jui Autocomplete so that when I click or focus on autocomplete textbox, it should display options.
I wrote following code and it seems to be working
$floorOptionsArray = ['Basement', 'Ground Floor', 'First floor', 'Second floor', 'Third floor'];
// $floorOptionsArray = array_combine($floorOptionsArray, $floorOptionsArray);
$model = new Customer();
echo $form->field($model, 'floor')
->widget(\yii\jui\AutoComplete::classname(), [
'value' => (!empty($model->floor) ? $model->floor : ''),
'clientOptions' => [
'source' => $floorOptionsArray,
'enabled' => true,
'minLength' => 0
],
'options' =>
[
'placeholder' => 'Floor',
'class' => 'form-control autocomplete-input-bg-arrow ',
'onclick' => "(function ( ) {
$( '#customer-floor' ).autocomplete( 'search', '' );
})();",
'onfocus' => "(function ( ) {
$( '#customer-floor' ).autocomplete( 'search', '' );
})();",
],
])->label(true);