all
My point is.
I need to create a custom report by passing a value from $valiable in view -> controller
my question is how to pass value from $valiable
now I can get value from another system by fix value in $valiable in controller.php
but I need to pass $valiable from view.php that selected after submit button.
something like this
here my code
index.php
<?php $form = ActiveForm::begin(); ?>
<div class="col-xs-12 col-sm-6 col-md-3">
<label class="control-label"> field1 </label>
<?php echo Select2::widget([
'name' => 'field1',
'data' => Report::itemAlias('field1'),
'options' => [
'placeholder' => 'Select Cost Center...',
],
'pluginOptions' => ['allowClear' => true,],
]); ?>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label class="control-label"> field2 </label>
<?php echo Select2::widget([
'name' => 'field2',
'data' => Report::itemAlias('field2'),
'options' => [
'placeholder' => 'Select Fund Center...',
],
'pluginOptions' => ['allowClear' => true,],
]); ?>
</div>
<div class="form-group" >
<?= Html::submitButton('process', ['class' => 'btn btn-warning ']) ?>
</div>
<?php ActiveForm::end(); ?>
in ReportController.php
public function actionIndex ()
{
$array = []; // for array result
$field1 = ''; // if fix value $field1 = 'a'; can pass a to $result
$field2 = ''; // if fix value $field2 = 'b'; can pass b to $result
if (Yii::$app->request->isPost)
{
$FISTL = $_POST['field1']; // view ~field1
$FIPEX = $_POST['field2']; // view ~field2
}
if($field1 !== '' && $field1 !== ''){ *// add if condition for get variable*
$connection = Yii::$app->sconnection->connectionToAnotherSystem(); // connection to another system
$result = $connection->getValue([
'field1' => $field1, // if fix value $field1 = 'a'; can pass a to $result
'field2' => $field2, // if fix value $field2 = 'b'; can pass b to $result
]);
$array = array(['value' =>$result]);//return value from another system
} $dataProvider = new ArrayDataProvider([
'allModels' => $array,
]);
return $this->render('index',
[
'dataProvider' => $dataProvider, // true data
]);
}
EDIT : i got what I want. in controller.php add if condition.
I don't get it at all
But suposing you have the other system's response in $result, it looks like an array; then you are asigning an array in the variable $array that have an assosiative value called 'value'.
The way to get the field1 value is
$array['value']['field1']
You should have a GridView like this in your view php file
<?= GridView::widget([
'dataProvider' => $dataProvider,
'columns' => [
...
'value.field1',
'value.field2',
...
],
]); ?>
That should works
Related
I am trying to display 2 piechart in same view, this is my view code :
<div class="panel-body form-horizontal">
{{-- <div id="morris-donut-chart"></div> --}}
<div class="form-group">
<div id="chart-div"></div>
#piechart('tgt','chart-div')
</div>
<div class="form-group">
<div id="chart-div2"></div>
#piechart('capai','chart-div2')
</div>
</div>
both success display, but the second chart has no data.
Piechart
i think the variable of data table is not problem , when i use dd(), it's has data.
Data of Capai
my controller code :
public function statistik()
{
$lava = new Lavacharts;
$ket = array("totalTarget" => 0, "totalCapai" => 0);
$target_ = Target::select('grup')
->selectRaw("SUM(nilai) AS jumlah")
->groupBy('grup')
->get()
->toArray();
$data = \Lava::DataTable();
$data->addStringColumn('Target')
->addNumberColumn('Percent');
foreach($target_ as $row){
$data->addRow([$row['grup'], $row['jumlah'] ]);
$ket["totalTarget"] += $row['jumlah'];
}
\Lava::PieChart('tgt', $data, [
'title' => 'Target :',
'height' => '300',
'is3D' => true,
]);
$capai_ = Faktur::select('nama')
->selectRaw('SUM(qty) AS jumlah')
->groupBy('sub_group')
->get()
->toArray();
$data_capai = \Lava::DataTable();
$data_capai->addStringColumn('Pencapaian')
->addNumberColumn('Percent');
foreach($capai_ as $row_){
$data_capai->addRow([$row_['nama'], $row_['jumlah'] ]);
$ket["totalCapai"] += $row_['jumlah'];
}
// dd($data_capai);
\Lava::PieChart('capai', $data_capai, [
'title' => 'Pencapaian :',
'height' => '300',
'is3D' => true,
]);
return view('dashboard', compact('lava', 'ket'));
}
Is there something I miss?
I already fixed it.
All I need is to convert data to Float.
I have a same field in foreach loop like below
foreach ( $subCategoryData as $k => $val) {
<?= $form->field($model, 'sub_category', ['template' => '{input}'])->textInput(['maxlength' => 255, 'class' => 'form-control required section_name', 'name' => "Category[sub_category][$k][name]"]) ?>
} ?>
I have ajax validation with custom method it is working fine.
But it is Working with only first input. Because it has same ID.
But when I changed it with 'inputOptions' => ['id' => 'myCustomId'] and make it unique with below and my ajax validation is not called.
foreach ( $subCategoryData as $k => $val) {
<?= $form->field($model, 'sub_category', ['template' => '{input}','inputOptions' => ['id' => "category-sub_category_".$k]])->textInput(['maxlength' => 255, 'class' => 'form-control required section_name', 'name' => "Category[sub_category][$k][name]"]) ?>
}
I have seen this solution here
https://github.com/yiisoft/yii2/issues/7627
and also seen this https://stackoverflow.com/a/28460442/2286537
But nothing work
can anyone help me ?
Your question is different from the posts you introduced.
You should use loadMultiple.
Example:
if (\Yii::$app->request->isAjax) {
if (\yii\base\Model::loadMultiple($model,\Yii::$app->request->post())) {
\Yii::$app->response->format = Response::FORMAT_JSON;
echo json_encode(ActiveForm::validateMultiple($model));
\Yii::$app->end();
}
}
if ( \yii\base\Model::loadMultiple($model, Yii::$app->request->post()) && \yii\base\Model::validateMultiple($model)) {
foreach ($model as $models) {
$models->save(false);
}
in view:
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
]);
I have two related models in hasToMany relation. The first is Invoices and the second is InvoiceItems. As a prototype process, I'm trying to conjugate the two models through the update view of the InvoicesController using the following code in actionUpdate of InvoicesController:
...
use common\models\Invoices;
use common\models\InvoicesSearch;
use common\models\InvoiceItems;
...
public function actionUpdate($id)
{
$model = $this->findModel($id);
$invoiceItems = new InvoiceItems();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$invoiceItems->invoice_id = $model->id;
if ($invoiceItems->load(Yii::$app->request->post()) && $invoiceItems->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
else{
// return false;
}
} else {
$invoiceItems->invoice_id = $model->id;
return $this->render('update', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]);
}
}
The following in update view:
<div class="invoices-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]) ?>
</div>
Finally, the following in _form view:
<div class="invoices-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'created')->textInput() ?>
<?= $form->field($model, 'type')->textInput(['maxlength' => true]) ?>
<hr />
<?= $form->field($invoiceItems, 'item_id')->textInput();?>
<?= $form->field($invoiceItems, 'unit_id')->textInput();?>
<?= $form->field($invoiceItems, 'qty')->textInput();?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Create') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
The above code succeeded in saving data in invoice_items table. However, the update view form has empty fields for InvoiceItems model. i.e item_id, unit_id and qty are empty in the update form after saving.
Notice: This is initial code, i.e I will work later to be able to add many items to the invoice, but now I just try to have one item related to the invoice.
Seems the update view is empty because you render and empty InvoceItmes ..
$invoiceItems = new InvoiceItems();
you render update view in else section and this section the value posted are not loaded
$model = $this->findModel($id);
$invoiceItems = new InvoiceItems();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$invoiceItems->invoice_id = $model->id;
if ($invoiceItems->load(Yii::$app->request->post()) && $invoiceItems->save()){
return $this->redirect(['view', 'id' => $model->id]);
}
else{
// return false;
}
} else {//****** here the $invoceItems is empty (It has just been created) ***
//$invoiceItems->invoice_id = $model->id;
$invoceItems= findInvoceItmesModel($model->id);
return $this->render('update', [
'model' => $model,
'invoiceItems' => $invoiceItems,
]);
}
for populate the data for $invoceItems you need somethings like
protected function findInvoiceItemsModel($id)
{
if (($model = InvociceItems::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
Obviously this is for a single model.. you must refactory form more than one..
I tried to submit a form using ajax. Below is my code:
controller code:
public function actionIndex($complaint, $work)
{
...
$this->render('index',array(
'model' => $model,
'work_order' => $work_order,
'work' => $work,
'complaint' => $complaint,
'work_complaint'=> $work_complaint
));
}
ajax action
public function actionCreate($complaint,$work)
{
...
$this->renderPartial('create',array(
'model' => $model,
'complaint' => $complaint,
'work' => $work,
'work_complaint' => $work_complaint,
'work_order' => $work_order,
'man_hour' => $man_hour,
'jobs' => $jobs,
));
}
my views
Create.php
<h1>Add Job</h1>
<?php $this->renderPartial('_form', array('model' => $model,
'work_complaint' => $work_complaint,
'work_order' => $work_order,
'man_hour' => $man_hour,
'jobs' => $jobs,
'complaint' => $complaint,
'work' => $work
)); ?>
my _form.php
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'post-form',
'enableAjaxValidation'=>false,
)); ?>
...
<div class="row buttons">
<div class="col-md-6 col-lg-6" >
<?php echo CHtml::ajaxSubmitButton ("Post",
array('complaintJob/create','complaint'=>$complaint,'work'=>$work),
array('update' => '#post')); ?>
</div>
</div>
<?php $this->endWidget(); ?>
</div><!-- form -->
my index.php
<div id="post">
<?php
$man_hour = ManHourMaster::model()->findByPk(1);
$jobs = Job::model()->with('job_category1')->findAll( "job_category1.is_separate = 0" );
$this->renderPartial('create',array(
'model' => $model,
'complaint' => $complaint,
'work' => $work,
'work_complaint' => $work_complaint,
'work_order' => $work_order,
'man_hour' => $man_hour,
'jobs' => $jobs,
));
?>
</div>
...
so when i run this code i get the form, and when i submit it, i basically get 2 copies of the same view.
i tried this one and it worked
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'complaint-job-form',
'enableAjaxValidation'=>true,
'clientOptions'=>array(
'validateOnSubmit'=>true,
'afterValidate'=>'js:function(form,data,hasError){
if(!hasError){
$.ajax({
"type":"POST",
"url":"'.CHtml::normalizeUrl(array('complaintJob/create','complaint'=>$complaint,'work'=>$work)).'",
"data":form.serialize(),
"success":function(data){
toastr.success("Saved successfully.", "Success");
$("#results").html(data);
$("#ComplaintJob_job_id").select2("val", "");
},
});
}
}'
),
)); ?>
In YII views folder i have test module and admin.php file to manage contents are below and i render form here where i put the code of form and dropdown in it , i want that grid refresh value of status change in dropdown
Suppose i select "Approved" than Grid show the data where status is approved
<?php
Yii::app()->clientScript->registerScript('dropdown', "
$('.dropdown-form form').submit(function(){
$('#testimonial-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
?>
<h1>Manage Testimonials</h1>
<div class="dropdown-form">
<?php $this->renderPartial('_dropdownform',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
/*
'status',
'approved_on',
'approved_by',
*/
array(
'class'=>'CButtonColumn',
),
),
)); ?>
Form below is _dropdownform , it contain a form and dropdown from this dropdown i am choosing the value of status
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('status', '', array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array(
'prompt' => 'Select Status',
'ajax' => array(
'type' => 'POST',
'url' => Yii::app()->createUrl('testimonial/loadthedata'),
//or $this->createUrl('loadcities') if '$this' extends CController
'update' => '#testimonial-grid', //or 'success' => 'function(data){...handle the data in the way you want...}',
'data' => array('status' => 'js:this.value'),
)));
?>
</div>
<div class="row buttons">
<?php //echo CHtml::submitButton('Search'); ?>
</div>
<?php $this->endWidget(); ?>
</div><!-- search-form -->
AND THE CODE IN MY CONTROLLER OR URL GIVEN IN DROPDOWN TO FETCH DATA IS FOLLOWING ACTION BUT I DONT KNOW HOW TO FETCH DATA FROM THIS FUNCTION AND PASS TO GRID VIEW
public function actionloadthedata() {
if (isset($_POST['status'])) {
$status = $_POST['status'];
if($status==0){
$status='New';
}
if($status==1){
$status='Approved';
}
if($status==2){
$status='Declined';
}
Testimonial::model()->findByAttributes(array('status'=>$status));
}
}
You can use CGridView property filterCssClass to link the grid filter, for example
$this->widget('CGridView', array(
'id' => 'my-list',
'filterCssClass' => '#filterFormId .filter',
And there is filter form
<?php $form = $this->beginWidget('CActiveForm', array(
'id' => 'filter-fomr-id',
)); ?>
<div class="filter clearfix">
<?php echo $form->dropDownList($model, 'name', [0=>'all', '1'=>'some else']); ?>
</div>
Replace #filterFormId .filter on jquery selector specific to you form. In other words, set id attribute for filter form, then use "#THISID .row".
In your gridview file, make sure you have this code:
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$('#ad-grid').yiiGridView('update', {
data: $(this).serialize()
});
return false;
});
");
then in the CGridView definition:
$this->widget('zii.widgets.grid.CGridView', array(
'id'=>'testimonial-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
...
array(
'name'=>'Status',
'filter'=>CHtml::dropDownList('YourModel[status]', $model->status, array(0 => 'New', 1 => 'Approved', 2 => 'Declined'), array('empty' => '--all--') ),
'value'=>'( $data->status == 0) ? "New": ( $data->status == 1) ? "Approved" : "Declined"',
'htmlOptions' => array(
'style' => 'width: 40px; text-align: center;',
),
),
...
array(
'class'=>'CButtonColumn',
),
),
));
// CGridView
In order to save if/else in the 'value' section, you can implement a method in your model that returns the string associated to the integer.
It works great, just with the default Yii admin.php view, which you can edit as much as you need.
Update
Added support for empty status, does not filter query results
Thanks #Alex for your help but i am successful to make filterdropdown for grid , code is following but will you please tell me that i want that grid show only values where status=New , how i can do when page load grid show values where status is New
but first i paste the working code of dropdown filter for grid
Here is my admin.php file
<?php
$this->breadcrumbs = array(
'Testimonials' => array('index'),
'Manage',
);
$this->menu = array(
array('label' => 'List Testimonial', 'url' => array('index')),
array('label' => 'Create Testimonial', 'url' => array('create')),
);
?>
<h1>Manage Testimonials</h1>
<!-----------drop down form------------->
<?php
Yii::app()->clientScript->registerScript('dropdownfilter', "
$('.dropdown-form form #staticid').change(function(){
$.fn.yiiGridView.update('testimonial-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<div class="dropdown-form">
<?php
$this->renderPartial('_dropdownfilter', array(
'model' => $model,
));
?>
</div><!-- search-form -->
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'testimonial-grid',
'dataProvider' => $model->search(),
// 'filter' => $model,
'columns' => array(
'id',
'created_by',
'test_name',
'test_email',
'comments',
'created_at',
'status',
array(
'class' => 'CButtonColumn',
),
),
));
?>
Here is my render partial form where i place the static drop dow
<div class="wide form">
<?php
$form = $this->beginWidget('CActiveForm', array(
'action' => Yii::app()->createUrl($this->route),
'method' => 'get',
));
?>
<div class="row">
<?php
echo CHtml::dropDownList('staticid', '', array('0' => 'New', '1' => 'Approved', '2' => 'Declined'), array(
// 'onChange' => 'this.form.submit()',
'ajax' => array(
'type' => 'POST', //request type
)));
?>
</div>
<?php $this->endWidget(); ?>
And Here is code of my adminaction in controller
public function actionAdmin() {
$model = new Testimonial('search');
$model->unsetAttributes(); // clear any default values
if (isset($_GET['staticid'])) {
$getStatus = $_GET['staticid'];
if ($getStatus == 0)
$status = 'New';
if ($getStatus == 1)
$status = 'Approved';
if ($getStatus == 2)
$status = 'Declined';
$model->status = $status;
}
if (isset($_GET['Testimonial']))
$model->attributes = $_GET['Testimonial'];
$this->render('admin', array(
'model' => $model,
));
}
Now i want that when i actionadmin triggered first time it show status=New values