YII2 - How to merge row yii2 gridview? - php

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.

Related

yii2 dep drop kartick dependencies

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 ...',
]
]);
?>

Yii2 - Keep child data in select option from parent dependent dropdown in uclead Tabular Input

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;',
]
],

Add filter on checkbox column Yii2 Gridview widget

Can you help me to add a filter on checkbox column on Grid view widget yii2? I used yii\grid\CheckboxColumn to add the check box column in the Gridview on my index.php. But I couldn't add a filter above the column as the other columns. Please look into my code below.
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id',
['label' => 'Client', 'attribute' => 'name', 'value' => 'client.view', 'format' => 'raw'],
'postCode',
'start',
'end',
[
'attribute' => 'categoryID',
'value' => 'category.name',
'filter' => ArrayHelper::map(Servicecategory::find()->where(['status' => true])->asArray()->all(), 'id', 'name')
],
[
'attribute' => 'status',
'headerOptions' => ['style' => 'width:12%'],
'value' => 'Status',
'filter' => array_filter(\app\models\Booking::$statuses),
'filterInputOptions' => ['class' => 'form-control', 'prompt' => 'All']
],
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'contentOptions' => ['class' => 'text-center'],
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp("' . $url . '")', 'checked' => $model->followUpEmailSent ? true : false, 'value' => $model->followUpEmailSent];
}
],
['class' => 'yii\grid\ActionColumn',
'headerOptions' => ['style' => 'width:10%'],
'template' => '{view} {approval} {update} {delete} ',
'buttons' => [
/* 'view' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-eye-open"></span>', ['/booking/review/' . $model->id], [
'title' => Yii::t('app', 'Review'),
]);
}, */
'approval' => function ($url, $model) {
return Html::a('<span class="glyphicon glyphicon-ok"></span>', ['/booking/approval/' . $model->id], [
'title' => Yii::t('app', 'Additional Details'),
'class' => 'error',
]);
}
],
],
],
]);
Following is the checkbox column.
['class' => 'yii\grid\CheckboxColumn',
'header' => 'follow Up',
'contentOptions' => ['class' => 'text-center'],
'checkboxOptions' => function($model, $key, $index) {
$url = \yii\helpers\Url::to(['booking/followup/' . $model->id]);
return ['onclick' => 'js:followUp("' . $url . '")', 'checked' => $model->followUpEmailSent ? true : false, 'value' => $model->followUpEmailSent];
}
],
Can someone help with this?
You may use your Gii tool-> CRUD generator to create your filter file.
Then you can pass your params to search model like this:
$searchModel = new SearchModel;
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
You will need to return your $dataProvider from SearchModel
Use the search file for implement filters on grid.
I suggest that do not use gridview filter in your case.
Write your search related code in search file and add checkbox on search form.
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
?>
<div class="ideas-search">
<?php $form = ActiveForm::begin([
'action' => ['index'],
'method' => 'get',
]); ?>
<?php echo $form->field($model, 'name[]')->checkboxList(
['a' => 'Item A', 'b' => 'Item B', 'c' => 'Item C']);
?>
<div class="form-group">
<?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
<?= Html::resetButton('Reset', ['class' => 'btn btn-default']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>

Show summary row and add it to the end of excel export

I'm trying to create summary row for my GridView which sums my quantity for current page and for all records seperately.
<?= GridView::widget([
'dataProvider' => $dataProvider,
'layout' => "{summary}\n{items}\n<div align='right'>{pager}</div>",
//'filterModel' => $searchModel,
'showPageSummary' => true,
'pageSummaryFunc' => GridView::F_SUM,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[
'class' => DataColumn::className(),
'attribute' => 'updated_at',
'format' => 'raw',
'value' => function ($model, $key, $index, $column){
return date('Y-m-d', $model->updated_at);
},
],
[
'label' => 'Ilość',
'attribute'=>'quantity',
'pageSummary' => true,
'value'=> function ($model, $key, $index, $column) {
return ($model->quantity) ? $model->quantity : '';
},
],
],
]); ?>
At the end i want to export sum for all records to my excel sheet at the bottom of my gridColumns. My export widget looks like:
$dataProviderAll->setSort([
'defaultOrder' => ['updated_at' => SORT_ASC]
]);
echo ExportMenu::widget([
'container' => ['class' => 'btn-group pull-right', 'role' => 'group'],
'dataProvider' => $dataProviderAll,
'columns' => $gridColumns,
'filename' => date('Y-m-d') . '_raport',
'target' => ExportMenu::TARGET_SELF,
'showConfirmAlert' => false,
'showColumnSelector' => false,
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Eksportuj dane',
'class' => 'btn btn-primary btn-md'
],
'exportConfig' => [
ExportMenu::FORMAT_HTML => null,
ExportMenu::FORMAT_TEXT => null,
ExportMenu::FORMAT_EXCEL => null,
ExportMenu::FORMAT_PDF => null
]
]);
?>
All columns of model are already exported, but i need to add summary row for some of them into created excel file.
Im getting now error like this: Setting unknown property: kartik\grid\GridView::pageSummaryFunc
Does someone know how can I get this result?
I have fixed part where I wanted to get sum per page by replacing class column from yii to kartik. –

Yii2 DynamicForm Input File Image always empty or NULL

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

Categories