I am developing a project using Codeigniter framework and in the reports page i need to have a form that has datatables structure so i can generate reports by day,month and year. but i dont know how to use datatables.
i have tried to add code like for example where it was written Y-m i added d-m-y but it doesn't work
Reports Controller:
defined('BASEPATH') OR exit('No direct script access allowed');
class Reports extends Admin_Controller
{
public function __construct()
{
parent::__construct();
$this->data['page_title'] = 'Stores';
$this->load->model('model_reports');
}
/*
* It redirects to the report page
* and based on the year, all the orders data are fetch from the database.
*/
public function index()
{
if(!in_array('viewReports', $this->permission)) {
redirect('dashboard', 'refresh');
}
$today_year = date('Y');
if($this->input->post('select_year')) {
$today_year = $this->input->post('select_year');
}
$parking_data = $this->model_reports->getOrderData($today_year);
$this->data['report_years'] = $this->model_reports->getOrderYear();
$final_parking_data = array();
foreach ($parking_data as $k => $v) {
if(count($v) > 1) {
$total_amount_earned = array();
foreach ($v as $k2 => $v2) {
if($v2) {
$total_amount_earned[] = $v2['net_amount'];
}
}
$final_parking_data[$k] = array_sum($total_amount_earned);
}
else {
$final_parking_data[$k] = 0;
}
}
$this->data['selected_year'] = $today_year;
$this->data['company_currency'] = $this->company_currency();
$this->data['results'] = $final_parking_data;
$this->render_template('reports/index', $this->data);
}
}
**Reports Model:**
<?php
class Model_reports extends CI_Model
{
public function __construct()
{
parent::__construct();
}
/*getting the total months*/
private function months()
{
return array('01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11', '12');
}
/* getting the year of the orders */
public function getOrderYear()
{
$sql = "SELECT * FROM orders WHERE paid_status = ?";
$query = $this->db->query($sql, array(1));
$result = $query->result_array();
$return_data = array();
foreach ($result as $k => $v) {
$date = date('Y', $v['date_time']);
$return_data[] = $date;
}
$return_data = array_unique($return_data);
return $return_data;
}
// getting the order reports based on the year and moths
public function getOrderData($year)
{
if($year) {
$months = $this->months();
$sql = "SELECT * FROM orders WHERE paid_status = ?";
$query = $this->db->query($sql, array(1));
$result = $query->result_array();
$final_data = array();
foreach ($months as $month_k => $month_y) {
$get_mon_year = $year.'-'.$month_y;
$final_data[$get_mon_year][] = '';
foreach ($result as $k => $v) {
$month_year = date('Y-m', $v['date_time']);
if($get_mon_year == $month_year) {
$final_data[$get_mon_year][] = $v;
}
}
}
return $final_data;
}
}
}
**View index**
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper">
<!-- Content Header (Page header) -->
<section class="content-header">
<h1>
Reports
</h1>
<ol class="breadcrumb">
<li><i class="fa fa-dashboard"></i> Home</li>
<li class="active">Reports</li>
</ol>
</section>
<!-- Main content -->
<section class="content">
<!-- Small boxes (Stat box) -->
<div class="row">
<div class="col-md-12 col-xs-12">
<form class="form-inline" action="<?php echo base_url('reports/') ?>" method="POST">
<div class="form-group">
<label for="date">Year</label>
<select class="form-control" name="select_year" id="select_year">
<?php foreach ($report_years as $key => $value): ?>
<option value="<?php echo $value ?>" <?php if($value == $selected_year) { echo "selected"; } ?>><?php echo $value; ?></option>
<?php endforeach ?>
</select>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<br /> <br />
<div class="col-md-12 col-xs-12">
<?php if($this->session->flashdata('success')): ?>
<div class="alert alert-success alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('success'); ?>
</div>
<?php elseif($this->session->flashdata('error')): ?>
<div class="alert alert-error alert-dismissible" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<?php echo $this->session->flashdata('error'); ?>
</div>
<?php endif; ?>
<div class="box">
<div class="box-header">
<h3 class="box-title">Total - Report</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<div class="chart">
<canvas id="barChart" style="height:250px"></canvas>
</div>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
<div class="box">
<div class="box-header">
<h3 class="box-title">Total Paid Orders - Report Data</h3>
</div>
<!-- /.box-header -->
<div class="box-body">
<table id="datatables" class="table table-bordered table-striped">
<thead>
<tr>
<th>Month - Year</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php foreach ($results as $k => $v): ?>
<tr>
<td><?php echo $k; ?></td>
<td><?php
echo $company_currency .' ' . $v;
//echo $v;
?></td>
</tr>
<?php endforeach ?>
</tbody>
<tbody>
<tr>
<th>Total Amount</th>
<th>
<?php //echo $company_currency . ' ' . array_sum($parking_data); ?>
<?php echo array_sum($results); ?>
</th>
</tr>
</tbody>
</table>
</div>
<!-- /.box-body -->
</div>
<!-- /.box -->
</div>
<!-- col-md-12 -->
</div>
<!-- /.row -->
</section>
<!-- /.content -->
</div>
<!-- /.content-wrapper -->
<script type="text/javascript">
$(document).ready(function() {
$("#reportNav").addClass('active');
});
var report_data = <?php echo '[' . implode(',', $results) . ']'; ?>;
$(function () {
/* ChartJS
* -------
* Here we will create a few charts using ChartJS
*/
var areaChartData = {
labels : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [
{
label : 'Electronics',
fillColor : 'rgba(210, 214, 222, 1)',
strokeColor : 'rgba(210, 214, 222, 1)',
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data : report_data
}
]
}
//-------------
//- BAR CHART -
//-------------
var barChartCanvas = $('#barChart').get(0).getContext('2d')
var barChart = new Chart(barChartCanvas)
var barChartData = areaChartData
barChartData.datasets[0].fillColor = '#00a65a';
barChartData.datasets[0].strokeColor = '#00a65a';
barChartData.datasets[0].pointColor = '#00a65a';
var barChartOptions = {
//Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
scaleBeginAtZero : true,
//Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,
//String - Colour of the grid lines
scaleGridLineColor : 'rgba(0,0,0,.05)',
//Number - Width of the grid lines
scaleGridLineWidth : 1,
//Boolean - Whether to show horizontal lines (except X axis)
scaleShowHorizontalLines: true,
//Boolean - Whether to show vertical lines (except Y axis)
scaleShowVerticalLines : true,
//Boolean - If there is a stroke on each bar
barShowStroke : true,
//Number - Pixel width of the bar stroke
barStrokeWidth : 2,
//Number - Spacing between each of the X value sets
barValueSpacing : 5,
//Number - Spacing between data sets within X values
barDatasetSpacing : 1,
//String - A legend template
legendTemplate : '<ul class="<%=name.toLowerCase()%>-legend"><% for (var i=0; i<datasets.length; i++){%><li><span style="background-color:<%=datasets[i].fillColor%>"></span><%if(datasets[i].label){%><%=datasets[i].label%><%}%></li><%}%></ul>',
//Boolean - whether to make the chart responsive
responsive : true,
maintainAspectRatio : true
}
barChartOptions.datasetFill = false
barChart.Bar(barChartData, barChartOptions)
})
</script>
Related
Custom filter datatables serverside not working in codeigniter 3 but no error, with join table database ... anyone can help me ? thx
MODEL
Rekap_m.php
var $column_order = array(null, 'bidang', 'skpd', 'kode', 'masalah', 'nomor', 'rincian_masalah', 'tahun_cipta', 'rak', 'dos', 'retensi', 'ket');
var $column_search = array('bidang', 'kode', 'nomor', 'skpd');
var $order = array('id_arsip' => 'asc');
private function _get_datatables_query()
{
if ($this->input->post('bidang')) {
$this->db->where('id_bidang', $this->input->post('bidang'));
}
if ($this->input->post('skpd')) {
$this->db->like('skpd', $this->input->post('skpd'));
}
if ($this->input->post('kode')) {
$this->db->like('kode', $this->input->post('kode'));
}
if ($this->input->post('masalah')) {
$this->db->like('masalah', $this->input->post('masalah'));
}
$this->db->select('*');
$this->db->from('arsip');
$this->db->join('bidang', 'bidang.id_bidang = arsip.id_bidang');
$i = 0;
foreach ($this->column_search as $item) {
if (#$_POST['search']['value']) {
if ($i === 0) {
$this->db->group_start();
$this->db->like($item, $_POST['search']['value']);
} else {
$this->db->or_like($item, $_POST['search']['value']);
}
if (count($this->column_search) - 1 == $i)
$this->db->group_end();
}
$i++;
}
if (isset($_POST['order'])) {
$this->db->order_by($this->column_order[$_POST['order']['0']['column']], $_POST['order']['0']['dir']);
} else if (isset($this->order)) {
$order = $this->order;
$this->db->order_by(key($order), $order[key($order)]);
}
}
function get_datatables()
{
$this->_get_datatables_query();
if (#$_POST['length'] != -1)
$this->db->limit(#$_POST['length'], #$_POST['start']);
$query = $this->db->get();
return $query->result();
}
function count_filtered()
{
$this->_get_datatables_query();
$query = $this->db->get();
return $query->num_rows();
}
function count_all()
{
$this->db->from('arsip');
return $this->db->count_all_results();
}
public function get_list_bidangs()
{
$this->db->select('*');
$this->db->from('arsip');
$this->db->join('bidang', 'bidang.id_bidang = arsip.id_bidang');
$this->db->order_by('id_arsip', 'asc');
$query = $this->db->get();
$result = $query->result();
$bidangs = array();
foreach ($result as $row) {
$bidangs[] = $row->bidang;
}
return $bidangs;
}
CONTROLLER
Rekap.php
function __construct()
{
parent::__construct();
check_not_login();
$this->load->model('rekap_m');
}
public function index()
{
$bidangs = $this->rekap_m->get_list_bidangs();
$opt = array('' => 'Semua Bidang');
foreach ($bidangs as $id_bidang) {
$opt[$id_bidang] = $id_bidang;
}
$data['form_bidang'] = form_dropdown('', $opt, '', 'id="bidang" class="form-control"');
$this->template->load('template', 'rekap/rekap_data', $data);
}
function ajax_list()
{
$list = $this->rekap_m->get_datatables();
$data = array();
$no = #$_POST['start'];
foreach ($list as $arsip) {
$no++;
$row = array();
$row[] = $no . ".";
$row[] = $arsip->bidang;
$row[] = $arsip->skpd;
$row[] = $arsip->kode;
$row[] = $arsip->masalah;
$row[] = $arsip->nomor;
$row[] = $arsip->rincian_masalah;
$row[] = $arsip->tahun_cipta;
$row[] = $arsip->rak;
$row[] = $arsip->dos;
$row[] = $arsip->retensi;
$row[] = $arsip->ket;
// add html for action
$data[] = $row;
}
$output = array(
"draw" => #$_POST['draw'],
"recordsTotal" => $this->rekap_m->count_all(),
"recordsFiltered" => $this->rekap_m->count_filtered(),
"data" => $data,
);
// output to json format
echo json_encode($output);
}
public function rekap()
{
$this->load->model('bidang_m');
$data['bidang'] = $this->bidang_m->get()->result();
$this->template->load('template', 'rekap/rekap_data', $data);
}
public function del($id)
{
$this->arsip_m->del($id);
if ($this->db->affected_rows() > 0) {
echo "<script>alert('Data Berhasil dihapus'); </script>";
}
echo "<script>window.location='" . site_url('rekap') . "'; </script>";
}
VIEW
rekap_data.php
<div class="row">
<!-- DataTable with Hover -->
<div class="col-lg-12">
<div class="card mb-4">
<div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<div class="col-md-4 offset-md-4">
<form id="form-filter">
<div class="form-horizontal">
<div class="form-group">
<div class="col-sm-9">
<div class="form-group">
<label for="bidang" class="col-sm-4 control-label">Bidang</label>
<?php echo $form_bidang; ?>
</div>
<div class="form-group">
<label for="skpd" class="col-sm-4 control-label">SKPD</label>
<input type="text" class="form-control" id="skpd">
</div>
<div class="form-group">
<label for="kode" class="col-sm-4 control-label">Kode</label>
<input type="text" class="form-control" id="kode">
</div>
<div class="form-group">
<label for="masalah" class="col-sm-4 control-label">Masalah</label>
<textarea class="form-control" id="masalah"></textarea>
</div>
<div class="form-group">
<button type="button" id="btn-filter" class="btn btn-primary">Filter</button>
<button type="button" id="btn-reset" class="btn btn-default">Reset</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="table-responsive p-3">
<table class="table align-items-center table-flush table-hover" id="dataTableHover">
<thead class="thead-light">
<tr>
<th>#</th>
<th>Bidang</th>
<th>SKPD</th>
<th>Kode</th>
<th>Masalah</th>
<th>Nomor</th>
<th>Rincian</th>
<th>Tahun</th>
<th>Rak</th>
<th>Dos</th>
<th>Retensi</th>
<th>Keterangan</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script type="text/javascript">
var table;
$(document).ready(function() {
table = $('#dataTableHover').DataTable({
"processing": true,
"serverSide": true,
"ajax": {
"url": "<?php echo site_url('rekap/ajax_list') ?>",
"type": "POST",
"data": function(data) {
data.id_bidang = $('#bidang').val();
data.skpd = $('#skpd').val();
data.kode = $('#kode').val();
data.masalah = $('#masalah').val();
}
},
"columnDefs": [{
"targets": [0],
"orderable": false,
}, ],
});
$('#btn-filter').click(function() {
table.ajax.reload();
});
$('#btn-reset').click(function() {
$('#form-filter')[0].reset();
table.ajax.reload();
});
});
</script>
the code above is the code that I use, there is no error but not working ... is there something wrong with my code, I ask for advice on what corrections if there are errors
Hello I am new to laravel. I am getting an error saying 'Property [pickupdate] does not exist on this collection instance.', after fowarding to 'overdue_pickup' view.
My Controller code
public function overdue_pickup(){
$id = "2";
$curr_date = date('m/d/yy');
$overdue_pickup = DB::table('archive_pickup')
->where('ridder_id_',$id)
->get();
if($overdue_pickup->pickupdate < $curr_date){
return view('overdue_pickup',['overdue_pickup' =>
$overdue_pickup]);
}else{
return "No Overdue Pickup";
}
}
My overdue_pickup view
<?php $i = 1; ?>
#foreach($overdue_pickup as $overdue_pickup)
<div class="col-md-offset-1 col-md-10">
<div class="box box-success">
<div class="box-header with-border">
<h3 class="box-title" style="padding:5px">Order No: <b><?php echo $i;?> {{$overdue_pickup->status}}</b></h3>
</div>
<div class="box-body">
<div class="col-md-offset-1 col-md-10">
<div style="overflow-x:auto;">
<p><i class="fa fa-dashboard"></i> <b>Pickup Time:</b> {{$overdue_pickup->pickuptime}}</p>
<p><i class="fa fa-dashboard"></i> <b>Delivery Time:</b> {{$overdue_pickup->deliverytime}}</p>
</div>
</div>
</div>
</div>
</div>
<?php $i++; ?>
#endforeach
Considering that your record for $id=2 is one,
Change
$assign_pickup = DB::table('archive_pickup')
->where('ridder_id',$id)
->get();
to first()
$assign_pickup = DB::table('archive_pickup')
->where('ridder_id',$id)
->first();
Then use
if($assign_pickup->pickdate > $curr_date){
return view('Ridder.assign',['assigned_pickup' => $assigned_pickup]);
}else{
return "No Overdue Pickup";
}
If not one then use foreach & no need to change get() statement,
foreach($assign_pickup as $assign_pick){
if($assign_pick->pickdate > $curr_date){
// ... your logic
}else{
// ..your logic
}
}
EDIT:
public function overdue_pickup(){
$id = "2";
$curr_date = date('m/d/yy');
$overdue_pickup = DB::table('archive_pickup')
->where('ridder_id_',$id)
->get();
return view('overdue_pickup',['overdue_pickup' =>
$overdue_pickup]);
}
In your view, you can just foreach loop through it,
#foreach($overdue_pickup as $overdue_pick)
#if($overdue_pick->pickdate > $curr_date)
{{-- show your view --}}
#else
<p class="text-warning">No Overdue Pickup</p>
#endif
#endforeach
I want to make dynamic input that save an image to my website.
I use yii2-dynamicform and Kartik input file extension. But, it always save it as null.
Thank you for your help
Ps : ... is other part of my code that not relevant with this question. :)
In controller :
<?php
namespace frontend\controllers;
use Yii;
use common\models\Election;
use common\models\ElectionSearch;
use common\models\Model;
use common\models\Kandidat;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use yii\web\Session;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
class ElectionController extends Controller
{
...
public function actionCreate()
{
$model = new Election();
$modelsKandidat = [new Kandidat];
if ($model->load(Yii::$app->request->post())){
$model->save();
$modelsKandidat = Model::createMultiple(Kandidat::classname());
Model::loadMultiple($modelsKandidat, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsKandidat) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsKandidat as $modelKandidat) {
$modelKandidat->id_election = $model->id_election;
if($modelKandidat->file = UploadedFile::getInstance($modelKandidat,'file'))
{
$imageName = date('dmyhis_').$modelKandidat->id_election;
$modelKandidat->file->saveAs('../../common/file/fotokandidat/'.$imageName.'.'.$modelKandidat->file->extension);
$modelKandidat->foto = $imageName.'.'.$modelKandidat->file->extension;
}
if (! ($flag = $modelKandidat->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id_election]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsKandidat' => $modelsKandidat,
]);
}
}
...
}
In _form :
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<div class="election-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data', 'id' => 'dynamic-form']]); ?>
...
<!-- mulai input kandidat !-->
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Vote</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 4, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsKandidat[0],
'formId' => 'dynamic-form',
'formFields' => [
'nama',
'deskripsi',
'riwayat',
'file',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsKandidat as $i => $modelsKandidat): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Kandidat</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelsKandidat->isNewRecord) {
echo Html::activeHiddenInput($modelsKandidat, "[{$i}]id_kandidat");
}
?>
<div class="row">
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]nama")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]deskripsi")->textarea(['rows' => 6]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]riwayat")->textarea(['rows' => 6]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]file")->fileInput() ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<!-- selesai input kandidat !-->
...
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
It's from #shoara/#zahraj answer :
I think you forgot to specify index for your file `
foreach ($modelsKandidat as $keyindex=>$modelKandidat)
{
$modelKandidat->id_election = $model->id_election;
if ($modelKandidat->file = UploadedFile::getInstance($modelKandidat, "[{$keyindex}]file")) {
.......
}
}
see demo controller and form part,imagine $modelCatalogOption in demo is your $model = new Election(); and $modelsOptionValue is your $modelsKandidat = [new Kandidat]; if you try and check your values in your controller I'm sure you can solve this problem easily. Pay attention to actionCreate
Is there any way to render partial view using AJAX that is a part of form which other part starts ActiveForm->begin() in main view?
Controller:
public function actionCreate()
{
$model = new order();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
try {
if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'New record has been saved.');
return $this->redirect(['index']);
}
}
catch(yii\db\IntegrityException $e) {
Yii::$app->getSession()->setFlash('error', 'Cannot save new record. Please try again.');
return $this->redirect(['index']);
}
}
else {
return $this->render('create', ['model' => $model, ]);
}
}
public function actionSpecialdetform()
{
$model = new order();
return $this->renderAjax('_specialform');
}
public function actionDetform()
{
$model = new order();
return $this->renderAjax('_form');
}
View (main - create.php):
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\order */
$this->title = 'Create';
$this->params['breadcrumbs'][] = ['label' => 'Orders', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="order-create">
<h1><?= Html::encode($this->title) ?></h1>
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true,]); ?>
<div class="panel panel-default wizard" id="order-wizard">
<div class="wizard-steps clearfix" id="form-wizard">
<ul class="steps">
<li data-target="#step1" class="active"><span class="badge badge-info">1</span>Order</li>
<li data-target="#step2"><span class="badge">2</span>Details</li>
</ul>
</div>
<div class="step-content clearfix">
<div class="step-pane active" id="step1">
<?php echo $form->field($model, 'order_date')->input(); ?>
</div>
<div class="step-pane" id="step2">
<div id="order-details">
</div>
</div>
<div class="actions pull-left">
<button type="button" class="btn btn-default btn-sm btn-prev wizard-btn" disabled="disabled"><i class="fa fa-angle-double-left" style="margin-right:5px"></i> Previous step</button>
<button type="button" class="btn btn-default btn-sm btn-next wizard-btn" data-last="Save">Next step <i class="fa fa-angle-double-right" style="margin-left:5px"></i></button>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$js = '
$(document).ready(function() {
$("#order-wizard").on("change", function(e, data) {
if(data.step===1 && data.direction==="next")
{
var date = $("#order-order_date").val();
if(date==="")
{
e.preventDefault();
}
var form = null;
if(date === "2015-01-01")
{
form = "/order/specialdetform"
}
else
{
form = "order/detform"
}
$.ajax({
url: form,
dataType: "html",
success: function(data) {
$("#order-details").html(data);
}
});
}
});
});
';
$this->registerJs($js, \yii\web\View::POS_END);
?>
Partial View - (_specialform.php):
<?= $form->field($model, 'promo_code')->input(); ?>
<?= $form->field($model, 'Surname')->input(); ?>
Partial View - (_form.php):
<?= $form->field($model, 'Surname')->input(); ?>
I don't want to just create one partial view, because this is only one different field, but it's an example.
I'm stuck with this script I'm using:
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link href="includes/css/style.css" type="text/css" rel="stylesheet" />
<link href="includes/css/wt-gallery.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="includes/js/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="includes/js/configuratie.js"></script>
<script type="text/javascript" src="includes/js/jquery.wt-gallery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#wait_1').hide();
$('#drop_1').change(function(){
$('#wait_1').show();
$('#result_1').hide();
$.get("func.php", {
func: "drop_1",
drop_var: $('#drop_1').val()
}, function(response){
$('#result_1').fadeOut();
setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
});
return false;
});
$('#wait_2').hide();
$('#drop_2').change(function(){
$('#wait_2').show();
$('#result_2').hide();
$.get("func.php", {
func: "drop_2",
drop_var: $('#drop_2').val()
}, function(response){
$('#result_2').fadeOut();
setTimeout("finishAjax2('result_2', '"+escape(response)+"')", 400);
});
return false;
});
$('#wait_3').hide();
$('#drop_3').change(function(){
$('#wait_3').show();
$('#result_3').hide();
$.get("func.php", {
func: "drop_3",
drop_var: $('#drop_3').val()
}, function(response){
$('#result_3').fadeOut();
setTimeout("finishAjax3('result_3', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response) {
$('#wait_1').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax2(id, response) {
$('#wait_2').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax3(id, response) {
$('#wait_3').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax_tier_three(id, response) {
$('#wait_2').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax_tier_four(id, response) {
$('#wait_3').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
function finishAjax_tier_five(id, response) {
$('#wait_4').hide();
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
</script>
</head>
<?php
$website = "it";
// configuratie file en db connect
include "includes/inc/config.inc.php";
include('db.php');
include_once "class/slider.class.php";
include('func.php');
$slideralbum = new slideralbum($dbo);
$sliders = $slideralbum->getSliderItems($website);
?>
<body>
<p>
<form name="product" action="" method="post">
<select name="drop_1" id="drop_1">
<option value="" selected="selected" disabled="disabled">Selecteer Merk</option>
<?php getTierOne(); ?>
</select>
<span id="wait_1" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_1" style="display: none;"></span>
<span id="wait_2" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_2" style="display: none;"></span>
<span id="wait_3" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_3" style="display: none;"></span>
<span id="wait_4" style="display: none;">
<img alt="Please Wait" src="ajax-loader.gif"/>
</span>
<span id="result_4" style="display: none;"></span>
<INPUT TYPE="button" VALUE="Refresh" onclick='location.reload()'>
</form>
</p>
<p>
<?php if(isset($_POST['submit'])){
$drop = $_POST['drop_1'];
$drop_2 = $_POST['drop_2'];
$drop_3 = $_POST['drop_3'];
$drop_4 = $_POST['drop_4'];
$drop_5 = $_POST['drop_5'];
?>
<table border="1" bordercolor="#B5B5B5" style="background-color:#FFFFFF" width="250" cellpadding="3" cellspacing="3">
<tr>
<td>Merk:</td>
<td><?php echo $drop;?></td>
</tr>
<tr>
<td>Model:</td>
<td><?php echo $drop_2;?></td>
</tr>
<tr>
<td>Bouwjaar:</td>
<td><?php echo $drop_3;?></td>
</tr>
<tr>
<td>Kleur:</td>
<td><?php echo $drop_4;?></td>
</tr>
</table>
<?php
}
?>
<div id="banner-block"> <!-- Begin of Slideshow -->
<div class="container">
<div class="wt-gallery" style="width:920px; height:375px;">
<div class="main-screen">
<?php if(isset($_POST['submit'])){
$drop = $_POST['drop_1'];
$drop_2 = $_POST['drop_2'];
$drop_3 = $_POST['drop_3'];
$drop_4 = $_POST['drop_4'];
$drop_5 = $_POST['drop_5'];
?>
<img src="images/<?php echo $drop_5;?>" alt="<?php echo $drop_5;?>" width="920" height="360"/>
<?php
}
?>
<noscript>
<!-- placeholder image when javascript is off -->
<img src="../images/triworks_abstract27.jpg" alt=""/>
</noscript>
</div>
<div class="cpanel">
<div class="thumbs-back"></div>
<div class="thumbnails">
<ul>
<?php $sliders = $slideralbum->getSliderItems($website, NULL);
foreach($sliders as $slider){
?>
<li effect="none">
<div>
<a href="<?php echo $slider->slider_img; ?>" height="360" width="720" alt="<?php echo $slider->slider_img; ?>" />
<img src="<?php echo $slider->slider_tmb; ?>" height="70" width="125" alt="<?php echo $slider->slider_tmb; ?>" />
</a>
</div>
<div class="data">
</div>
</li>
<?php
}
?>
</ul>
</div>
<div class="thumbs-fwd"></div>
</div>
</div>
</div>
</div>
</body>
</html>
func.php
<?php
//**************************************
// Page load dropdown results //
//**************************************
function getTierOne()
{
$result = mysql_query("SELECT DISTINCT make FROM vehicles ORDER BY make ASC")
or die(mysql_error());
while($tier = mysql_fetch_array( $result ))
{
?>
<option value="<?php echo $tier['make'];?>"<?php echo (isset($_POST['drop_1']) && $_POST['drop_1'] == $tier['make']) ? ' selected="selected"' : '' ; ?>><?php echo $tier['make'];?></option>
<?php
}
}
//**************************************
// First selection results //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_1" ) {
drop_1($_GET['drop_var']);
}
function drop_1($drop_var)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT model FROM vehicles WHERE make='$drop_var' ORDER BY model")
or die(mysql_error());
echo '<select name="drop_2" id="drop_2">
<option value=" " disabled="disabled" selected="selected">Selecteer Model</option>';
while($drop_2 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_2['model'].'">'.$drop_2['model'].'</option>';
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_2').hide();
$('#drop_2').change(function(){
$('#wait_2').show();
$('#result_2').hide();
$.get(\"func.php\", {
func: \"drop_2\",
drop_var: $('#drop_1').val(),
drop_var2: $('#drop_2').val()
}, function(response){
$('#result_2').fadeOut();
setTimeout(\"finishAjax_tier_three('result_2', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
//**************************************
// Second selection results //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_2" ) {
drop_2($_GET['drop_var'], $_GET['drop_var2']);
}
function drop_2($drop_var, $drop_var2)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT year FROM vehicles WHERE make='$drop_var' AND model='$drop_var2'")
or die(mysql_error());
echo '<select name="drop_3" id="drop_3">
<option value=" " disabled="disabled" selected="selected">Selecteer Jaar</option>';
while($drop_3 = mysql_fetch_array( $result ))
{
echo '<option value="'.$drop_3['year'].'">'.$drop_3['year'].'</option>';
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_3').hide();
$('#drop_3').change(function(){
$('#wait_3').show();
$('#result_3').hide();
$.get(\"func.php\", {
func: \"drop_3\",
drop_var: $('#drop_1').val(),
drop_var2: $('#drop_2').val(),
drop_var3: $('#drop_3').val()
}, function(response){
$('#result_3').fadeOut();
setTimeout(\"finishAjax_tier_four('result_3', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
//**************************************
// Third selection results //
//**************************************
if (isset($_GET['func'])&& $_GET['func'] == "drop_3" ) {
drop_3($_GET['drop_var'], $_GET['drop_var2'], $_GET['drop_var3']);
}
function drop_3($drop_var, $drop_var2, $drop_var3)
{
include_once('db.php');
$result = mysql_query("SELECT DISTINCT color FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3'")
or die(mysql_error());
echo '<select name="drop_4" id="drop_4">
<option value=" " disabled="disabled" selected="selected">Selecteer Kleur</option>';
while($drop_4 = mysql_fetch_array( $result ))
{
if ($drop_4['color'] != "") {
echo '<option value="'.$drop_4['color'].'">'.$drop_4['color'].'</option>';
}
}
echo '</select>';
echo "<script type=\"text/javascript\">
$('#wait_4').hide();
$('#drop_4').change(function(){
$('#wait_4').show();
$('#result_4').hide();
$.get(\"func.php\", {
func: \"drop_4\",
drop_var: $('#drop_1').val(),
drop_var2: $('#drop_2').val(),
drop_var3: $('#drop_3').val(),
drop_var4: $('#drop_4').val()
}, function(response){
$('#result_4').fadeOut();
setTimeout(\"finishAjax_tier_five('result_4', '\"+escape(response)+\"')\", 400);
});
return false;
});
</script>";
}
//**************************************
// Fourth selection results //
//**************************************
if(isset($_GET['func'])&& $_GET['func'] == "drop_4" ) {
drop_4($_GET['drop_var'], $_GET['drop_var2'], $_GET['drop_var3'], $_GET['drop_var4']);
}
function drop_4($drop_var, $drop_var2, $drop_var3, $drop_var4)
{
include_once('db.php');
$result = mysql_query("SELECT * FROM vehicles WHERE make='$drop_var' AND model='$drop_var2' AND year='$drop_var3' AND color='$drop_var4'")
or die(mysql_error());
while($drop_5 = mysql_fetch_array( $result ))
{
if ($drop_5['img'] != "") {
echo '<input type="checkbox" name="drop_5" id="drop_5" style="display:none;" checked value="'.$drop_5['img'].'"/>';
}
}
echo '<input type="submit" name="submit" value="Submit" />';
}
?>
After I selected all my dropdown items and press submit it is working good but all the selected values are gone...
If you want to change color you have to go to the whole dropdown list again. Is it possible to keep all the selected values after submit?
Thanks in advance
Kind Regards
Joep
You are using GET requests to display each dropdown list in turn, and then using a POST request to submit your completed form. You should make sure that all the dropdowns are displayed after the POST request.
In index.php, I think you could try something like that :
<span id="result_1" style="display: none;">
<?php
if (isset($_POST['submit']) {
drop_1($_POST['drop_1']);
}
?>
</span>
...
<span id="result_2" style="display: none;">
<?php
if (isset($_POST['submit']) {
drop_2($_POST['drop_1'], $_POST['drop_2']);
}
?>
</span>
...
<span id="result_3" style="display: none;">
<?php
if (isset($_POST['submit']) {
drop_3($_POST['drop_1'], $_POST['drop_2'], $_POST['drop_3']);
}
?>
</span>
etc...
Anyway, the idea is to reuse the functions that build your dropdowns, based on the values in the $_POST.