Yii2 stop page re-load while clicking on pagination - pagination

I have an index page in which I am calling some views based on a selection. Also, I have a form that is submitting on every sent request.
<section class="container-fluid">
<div class="box">
<div class="box-body">
<form action="index" method="post" >
<select required id="s" name="dtype" class="dropdown"
style="float: left; text-align: left;width: 20%; margin: 10px;">
<option value="400">Select Data Type</option>
<option value="401"<?php if(isset($_POST['dtype']) && $_POST['dtype'] == '401')
echo 'selected= "selected"';
?>>Current</option>
<option value="402"<?php if(isset($_POST['dtype']) && $_POST['dtype'] == '402')
echo 'selected= "selected"';
?>>Voltage</option>
<option value="403"<?php if(isset($_POST['dtype']) && $_POST['dtype'] == '403')
echo 'selected= "selected"';
?>>kWh</option>
</select>
<input style="float: left; text-align: left; margin: 10px; width: 15%" type="text" id="name" name="msn" required
minlength="4" maxlength="15" size="15" placeholder="MSN"
value="<?php echo isset($_POST['msn']) ? htmlspecialchars($_POST['msn'], ENT_QUOTES) : ''; ?>">
<?php
echo DateTimePicker::widget([
'name' => 'datetime_10',
'id'=>'start',
'value' => Yii::$app->request->post('datetime_10', null),
'options' => [
'placeholder' => 'Start',
'autocomplete' => 'off',
'required' =>true,
],
'convertFormat' => false,
'pluginOptions' => [
'format' => 'yyyy-mm-dd hh:i:ss',
//'startDate' => '01-Mar-2014 12:00 AM',
'todayHighlight' => true,
'autoclose' => true,
]
]);
echo DateTimePicker::widget([
'name' => 'datetime_11',
'id'=>'end',
'value' => Yii::$app->request->post('datetime_11', null),
'options' => [
'placeholder' => 'End',
'autocomplete' => 'off',
'required' =>true,
],
'convertFormat' => false,
'pluginOptions' => [
'format' => 'yyyy-mm-dd hh:i:ss',
//'startDate' => '01-Mar-2014 12:00 AM',
'todayHighlight' => true,
'autoclose' => true,
]
]);
?>
<input type="submit" value="Query" id="btnSubmit" class="btn btn-success pull-right" style="margin: 5px" />
</form>
</div>
</div>
</section>
<section class="content">
<div class="box">
<div class="box-body">
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?php
if($type == '401')//current
{
$columns = [
[
'class' => 'yii\grid\SerialColumn',
],
'Device_ID',
'Customer_ID',
'MSN',
'Current_Phase_1',
'Current_Phase_2',
'Current_Phase_3',
'Data_Date_Time',
];
echo $this->render('_currentChart', [
'dataProvider' => $dataProvider,
]) ;
}else if($type == '402')//voltages
{
$columns = [
[
'class' => 'yii\grid\SerialColumn',
],
'Device_ID',
'Customer_ID',
'MSN',
'Voltage_Phase_1',
'Voltage_Phase_2',
'Voltage_Phase_3',
'Data_Date_Time',
];
echo $this->render('_voltageChart', [
'dataProvider' => $dataProvider,
]) ;
}
else if($type == "403")
{
$columns = [
[
'class' => 'yii\grid\SerialColumn',
],
'Device_ID',
'Customer_ID',
'MSN',
'kWh_Total',
'Data_Date_Time',
];
echo $this->render('_kwhChart', [
'dataProvider' => $dataProvider,
]) ;
}
else if($type == "404")
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'Device_ID',
'Customer_ID',
'MSN',
'Total_Power',
'Data_Time',
];
echo $this->render('_totalChart', [
'dataProvider' => $dataProvider,
]) ;
}
else
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'device_id',
'cust_id',
'msn',
'kwh_t',
'voltage_p1',
'voltage_p2',
'voltage_p3',
'current_p1',
'current_p2',
'current_p3',
'data_date_time',
];
}
?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => $columns
]);
?>
</div>
</div>
</section>
Current Chart
<?PHP
$dataPointsC1 = array();
$dataPointsC2 = array();
$dataPointsC3 = array();
$model = $dataProvider->getModels();
foreach ($model as $row){
// pushing for voltages
array_push($dataPointsC1, array("label"=>$row['Data_Date_Time'],"y"=>$row['Current_Phase_1']));
array_push($dataPointsC2, array("label"=>$row['Data_Date_Time'],"y"=>$row['Current_Phase_2']));
array_push($dataPointsC3, array("label"=>$row['Data_Date_Time'],"y"=>$row['Current_Phase_3']));
}
?>
<div id="chartContainer1" style="width: 100%; height: 300px;display: inline-block;">
</div>
<script>
var chart1 = new CanvasJS.Chart("chartContainer1", {
exportEnabled: true,
animationEnabled: true,
zoomEnabled: true,
theme: "light1",
title:{
text: "Current"
},
legend:{
cursor: "pointer",
verticalAlign: "bottom",
horizontalAlign: "center",
itemclick: toggleDataSeries
},
data: [
{
type: "line",
//lineColor:"yellow",
// legendMarkerColor: "yellow",
name: "Current(Phase-1)",
indexLabel: "{y}",
//yValueFormatString: "V1#0.##",
showInLegend: true,
dataPoints: <?php echo json_encode($dataPointsC1, JSON_NUMERIC_CHECK); ?>
},
{
type: "line",
// lineColor:"orange",
// legendMarkerColor: "orange",
name: "Current(Phase-2)",
indexLabel: "{y}",
//yValueFormatString: "V2#0.##",
showInLegend: true,
dataPoints: <?php echo json_encode($dataPointsC2, JSON_NUMERIC_CHECK); ?>
},
{
type: "line",
// lineColor:"purple",
// legendMarkerColor: "purple",
name: "Current(Phase-3)",
indexLabel: "{y}",
//yValueFormatString: "V3#0.##",
showInLegend: true,
dataPoints: <?php echo json_encode($dataPointsC3, JSON_NUMERIC_CHECK); ?>
}
]
});
chart1.render();
function toggleDataSeries(e){
e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible);
chart1.render();
}
</script>
Screen before any filter
Screen After filter
The pages also come with pagination. When I click on the pagination the entire page reloads and sets to it's original state.
How can I manage this ?

use pjax
https://www.yiiframework.com/doc/api/2.0/yii-widgets-pjax
in your index view
Pjax::begin();
//your reload code
Pjax::end();

Related

Vuetify v-data-table search.filter not showing any results

Getting data back from our API but built in Vuetify search/filter is not working. I think it has to do with the data coming back being nested in an object. When typing in the search filter i get "No matching records found" after the first character, when removing the search term the full data table is displayed. Thanks in advance for any help.
<template>
<v-container
fill-height
fluid
grid-list-xl
>
<v-layout
justify-center
wrap
>
<v-flex
md6
>
<material-card
color="black"
title="Users"
>
<v-text-field
v-model="search"
append-icon="mdi-magnify"
label="Search"
single-line
hide-details
></v-text-field>
<v-data-table
:headers="headers"
:items="userData"
:search="search"
hide-actions
>
<template
slot="headerCell"
slot-scope="{ header }"
>
<span
class="subheading font-weight-light text-dark text--darken-3"
v-text="header.text"
/>
</template>
<template
slot="items"
slot-scope="{ item }"
>
<td>
<v-avatar slot="offset" class="mx-auto d-block" size="100">
<img v-if="item.ProfileImage==null" src="img/conectrlogo.jpg">
<img v-else v-bind:src= "item.ProfileImage">
</v-avatar></td>
<td><v-btn text-small outlined color="primary" #click= "goToUserProfile(item.Id)">{{ item.Id}}</v-btn></td>
<td>{{ item.Username}}</td>
<td>{{ item.Name}}</td>
</template>
</v-data-table>
</material-card>
</v-flex>
</v-layout>
</v-container>
</template>
Script
<script>
import axios from 'axios'
export default {
mounted()
{
console.log("got into mounted function");
this.getResults();
},
data () {
return {
customFilter: function (items, search, filter, headers) {
search = search.toString().toLowerCase()
if (search.trim() === '') return items
const props = headers.map(h => h.value)
return items.filter(item => props.some(prop => filter(getObjectValueByPath(item, prop, item[prop]), search)))
},
userData:[],
totalUsers:0,
showResults:true,
search:'',
headers:[
{
text: 'User',
value: 'profileimage',
align: 'center',
width: '50px',
sortable:false
},
{
text: 'id',
value: 'id',
align: 'center',
width: '100px',
sortable:false
},
{
text: 'Username', value: 'username',
align: 'left',
sortable: false,
width: '50px'
},
{
text: 'Name', value: 'name',
align: 'left',
sortable: true,
width: '50px'
}
]
}
},
computed:{
},
methods: {
goToUserProfile: function(Id)
{
console.log("avatar clicked:"+Id);
this.$router.push('/user-profile/'+Id)
},
getResults (){
console.log("got into the all users endpoint");
console.log(this.$baseUrl+'/admin/users');
// axios.get(this.$baseUrl+'/admin/users',
// {withCredentials: true}).then ( response => {
// this.userData=response.data.Users;
// this.totalUsers = response.data.UserCount;
// console.log("all user response:"+this.userData);
// });
//this.showResults=true;
axios.defaults.withCredentials = true;
axios(this.$baseUrl+'/admin/users', {
method: 'GET',
withCredentials: true,
crossDomain:true
}).then(res => {
console.log(res);
this.userData=res.data.Users;
this.totalUsers = res.data.UserCount;
console.log("all user response:"+this.userData);
}).catch(err => {
console.log("got an error");
console.log(err);
})
},
initialize()
{
},
}
}
</script>

Vuetify - Listen for v-menu activator?

I would like to do some actions when the v-menu is opened up in Vuetify? How can I do that? Can I watch the activator somehow?
Thank you jacek,
Listen to the v-model of the v-menu like this.
<template>
<div class="text-center">
<v-menu offset-y v-model="menu_model">
<template v-slot:activator="{ on }">
<v-btn color="primary" dark v-on="on">{{ buttonText }}</v-btn>
</template>
<v-list>
<v-list-item v-for="(item, index) in items" :key="index">
<v-list-item-title>{{ item.title }}</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
</div>
</template>
<script>
export default {
data: () => ({
items: [
{ title: "Click Me" },
{ title: "Click Me" },
{ title: "Click Me" },
{ title: "Click Me 2" }
],
menu_model: "",
buttonText: "Click to open menu"
}),
watch: {
menu_model(menu_open) {
if (menu_open === true) {
this.buttonText = "Menu Open";
} else {
this.buttonText = "Click to open menu";
}
}
}
};
</script>
CodePen
As per Vuetify 2.6.3, we can make use of 'value' from activator slot. Here is the link
Here is the link to Codepen
<template>
<div id="app">
<v-app id="inspire">
<div class="text-center">
<v-menu offset-y v-model="menu_model">
<template v-slot:activator="{ on, value }">
<v-btn
color="primary"
dark
v-on="on">
{{ value ? 'Click to open menu' : 'Menu Open' }}
</v-btn>
</template>
<v-list>
<v-list-item
v-for="(item, index) in items"
:key="index">
<v-list-item-title>{{ item.title }}</v-list-item-title>
</v-list-item>
</v-list>
</v-menu>
</div>
</v-app>
</div>
</template>
<script>
new Vue({
el: '#app',
vuetify: new Vuetify(),
data: () => ({
items: [
{ title: 'Click Me' },
{ title: 'Click Me' },
{ title: 'Click Me' },
{ title: 'Click Me 2' },
],
}),
})

Yii2 search with empty param throws all records

There are 3 search fields in view2.php, search is working properly when i enter something into search field and hit search button. But the problem is when I hit search/Enter button without entering anything into search fields, it displays all the entries related to that model from DB.
Below is my Machine model:
public function search($params)
{
$query = Supplier::find();
$query->joinWith(['user', 'cities', 'industrialareas','supplierMachines', 'subCategory', 'types0','supplierCertificates' ]);
$dataProvider = new ActiveDataProvider([
'query' => $query,
'pagination' => [
'pageSize' => 20,
],
]);
if (!($this->load($params) && $this->validate())) {
$query->where('1 <> 1');
}
else {
// grid filtering conditions
$query->andFilterWhere([
'id' => $this->id,
'yoe' => $this->yoe,
]);
$query->andFilterWhere(['like', 'company_constitution', $this->company_constitution])
->andFilterWhere(['like', 'street', $this->street])
->andFilterWhere(['like', 'locality', $this->locality])
}
return $dataProvider;
}
}
machine controller which calls view2 function(it displays search fields)
public function actionView2()
{
//Display machines based on the customer search
$searchModel = new SupplierMachineSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
// render
return $this->render('view2', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
View2.php
<?= $form->field($searchModel, 'enter_city')->widget(AutoComplete::classname(), [
'options' => ['placeholder' => 'Select a city ...', 'class' => 'form-control'],
'clientOptions' => [
'source' => ArrayHelper::getColumn($data, 'city_name'), ],
]) ?>
<?= $form->field($searchModel, 'enter_iarea')->widget(AutoComplete::classname(), [
'options' => ['placeholder' => 'Select a iarea ...', 'class' => 'form-control'],
'clientOptions' => [
'source' => ArrayHelper::getColumn($data1, 'iarea_name'), ],
]) ?>
<?= $form->field($searchModel, 'machine')->widget(AutoComplete::classname(), [
'options' => ['placeholder' => 'Select a iarea ...', 'class' => 'form-control'],
'clientOptions' => [
'source' => ArrayHelper::getColumn($all, 'name' ), ],
]) ?>
<?= Html::activeHiddenInput($searchModel, 'id')?>
<div class="form-group">
<?= Html::submitButton('Apply', ['class' => 'btn btn-success']) ?>
<?= Html::a('Reset', ['view2']);?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?=
ListView::widget([
'dataProvider' => $dataProvider,
'itemView' => '_viewmain',
'viewParams' => [
'fullView' => false,
'context' => 'main-page',
],
]);
Check if the search parameters, once loaded, are empty:
if ( !($this->load($params) && $this->validate()) or
(empty($this->search_param1) and empty($this->search_param2) and empty($this->search_param3)) ) {
$query->where('1 <> 1');
}

yii2: SqlDataProvider with pagination and searcModel getting error preg_match() expects parameter 2 to be string, object given

i want to show data using sqlDataProvider to gridview from different table and calculate it, here my code in siteController.php
public function actionSyahriyah()
{ $searchModel = new SyahriyahSearch();
$db = Yii::$app->db;
$bayar = $db ->createCommand('SELECT sy.no_syahriyah, sy.banyak, sa.nama, sy.tgl, sa.tarif
FROM santri sa, syahriyah sy
WHERE sa.no_induk = sy.no_induk
ORDER BY sy.tgl');
$dataProvider = new SqlDataProvider([
'sql' => $bayar,
'pagination' => [
'pageSize' => 5
],
]);
return $this->render('syahriyah',[
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
and this is the gridview:
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
// ['class' => 'yii\grid\SerialColumn'],
'tgl',
'banyak',
],
'export' => false,
]);
?>
You can use dataProvider
<?php
$bayar = $db ->createCommand('SELECT sy.no_syahriyah, sy.banyak, sa.nama, sy.tgl, sa.tarif
FROM santri sa, syahriyah sy
WHERE sa.no_induk = sy.no_induk
ORDER BY sy.tgl');
$dataProvider = new SqlDataProvider([
'sql' => $bayar,
'pagination' => [
'pageSize' => 5
],
],
]);
?>

Error: This page can't be reached in Kartik Yii2 Export

In Kartik Yii2 Export, While exporting as Excel am getting This Page Cant't Reached Error in Localhost.
if i export as Text or CSV, export get worked but if i open the exported file Text or CSV, Half the
report is printing like html code
Help will be really appreciated.
GridCode:
<?php $gridColumns = [
['class' => 'yii\grid\SerialColumn'],
'membercode',
'member_name',
[
'attribute' => 'payment_category',
'format' => 'raw',
'label' => 'Payment Category',
'value' => function($model, $key, $index, $grid) {
$temp = $model->payment_category;
$si = Category::find()->where(['category_id' => $temp])->one();
return $si['category_name'];
},
],
'member_gender',
'member_address:ntext',
'payment_date',
'amount',
'receipt_no',
'payment_mode',
'pledge_amount',
'young_amount',
'tv_amount',
'building_amount',
[
'attribute' => 'payment_subcategory',
'format' => 'raw',
'value' => function($model, $key, $index, $grid) {
$exp = explode(',', $model->payment_subcategory);
$relation_name = ArrayHelper::map(Subcategory::find()->where(['subcategory_id' => $exp])->all(), 'subcategory_id', 'subcategory_name');
$relation = implode(',', $relation_name);
return $relation;
},
'filter' => Html::activeDropDownList($searchModel, 'payment_subcategory', ArrayHelper::map(Subcategory::find()->asArray()->all(), 'id', 'subcategory_name'),['class'=>'form-control','multiple' => true]),
],
['class' => 'yii\grid\ActionColumn'],
]; ?>
<?= ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'columnSelectorOptions'=>[
'label' => 'Columns',
'class' => 'btn btn-danger'
],
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Export All',
'class' => 'btn btn-primary'
]
]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'pager' => [
'firstPageLabel' => 'First',
'lastPageLabel' => 'Last',
],
]); ?>
Above is my Grid view Code.
Help will be really appreciated.
Updated:
Error geeting while exporting as CSV:
Error geeting while exporting as EXCEL
There is an issue in your gridview, one of the field in gridview carries "=" equal to sign. please check it out PhpOffice/PhpExcel
Try exportConfig settings this
<?= ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => $gridColumns,
'columnSelectorOptions'=>[
'label' => 'Columns',
'class' => 'btn btn-danger'
],
'fontAwesome' => true,
'dropdownOptions' => [
'label' => 'Export All',
'class' => 'btn btn-primary'
]
'exportConfig' => [
ExportMenu::FORMAT_HTML => false,
ExportMenu::FORMAT_TEXT => false,
],
]); ?>
Try this code for your GridVew::Widget:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => $gridColumns,
'exportConfig'=> [
GridView::CSV=>[
'label' => 'CSV',
'icon' => '',
'iconOptions' => '',
'showHeader' => false,
'showPageSummary' => false,
'showFooter' => false,
'showCaption' => false,
'filename' => 'yii',
'alertMsg' => 'created',
'options' => ['title' => 'Semicolon - Separated Values'],
'mime' => 'application/csv',
'config' => [
'colDelimiter' => ";",
'rowDelimiter' => "\r\n",
],
],
],
]);

Resources