Unable to set partial view in my index page yii2 - yii2

I am trying to render a partial view at index page to show a chart when a certain condition gets true by doing the following.
Index.php
<?PHP
.
.
.
.
else if($type == "403")
{
$columns = [
['class' => 'yii\grid\SerialColumn'],
'Device_ID',
'Customer_ID',
'MSN',
'kWh',
'Data_Date_Time',
];
$this->render('_kwhChart', [
'dataProvider' => $dataProvider,
]) ;
}
.
.
.
.
?>
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'filterModel' => $searchModel,
'columns' => $columns
]);
?>
When a certain condition gets true I am able to see the updated gridview values but not the partial view i.e. chart.
Patial view
<?PHP
$dataPointskWh = array();
$model = $dataProvider->getModels();
foreach ($model as $row)
{
// pushing for kwh values
array_push($dataPointskWh,
array("label"=>$row['Data_Date_Time'],"y"=>$row['kWh']));
}
?>
<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: "Voltages"
},
legend:{
cursor: "pointer",
verticalAlign: "bottom",
horizontalAlign: "center",
itemclick: toggleDataSeries
},
data: [
{
type: "column",
lineColor:"red",
legendMarkerColor: "red",
name: "kWh",
indexLabel: "{y}",
//yValueFormatString: "V1#0.##",
showInLegend: true,
dataPoints: <?php echo json_encode($dataPointskWh, JSON_NUMERIC_CHECK); ?>
}
]
});
chart1.render();
function toggleDataSeries(e){
e.dataSeries.visible = !(typeof (e.dataSeries.visible) === "undefined" || e.dataSeries.visible);
chart1.render();
}
Note: I am using a submit button, and the page refresh every time when submit button is clicked.
How can I achieve this?
Any help would be highly appreciated.

You don't render the render() .. you need .. echo
echo $this->render('_kwhChart', [
'dataProvider' => $dataProvider,
]) ;
or
<?= $this->render('_kwhChart', ['dataProvider' => $dataProvider, ]) ?>;

Related

how do I display the same data and aggregate it in one line in yii2?

MODEL
public function getJumlah()
{
return $this->hasMany(AssetMaster::className(), ['id_asset_received' => 'received_date'])
->leftJoin('asset_received','asset_received.id_asset_received = asset_master.id_asset_master')
->groupBy('received_date')
->count();
}
VIEW
<?= GridView::widget(
[
'behaviors' => [
[
'class' => '\dosamigos\grid\behaviors\GroupColumnsBehavior',
'extraRowColumns' => ['assetMaster.asset_name'],
'extraRowValue' => function($model, $key, $index, $totals) {
return '<span class="label label-warning">' . $model['received_year'] . '</span>';
},
'mergeColumns' => ['assetMaster.asset_name','received_year']
]
],
'columns' => [
'assetMaster.asset_name',
received_date',
'received_year',
'Jumlah'
],
'dataProvider' => $dataProvider,
'layout' => "\n{items}\n{pager}"
]
);
?> '
i want sum "nama barang " every search i use , for now "jumlah" is the result of COUNT
and make it into just one line, is there anyone who can help

Change name of \yii\imperavi\Widget widget

I want to change the name of the form field from Page[body] to body lets say. Following is the code for WYSIWYG editor.
<?php echo $form->field($model, 'body')->widget(
\yii\imperavi\Widget::className(),
[
'plugins' => ['fontcolor', 'video'],
'options'=>[
'minHeight'=>400,
'maxHeight'=>400,
'buttonSource'=>true,
//'imageUpload'=>Yii::$app->urlManager->createUrl(['/file-storage/upload-imperavi'])
]
]
) ?>
I don't want to change my model just the name of the form field submitted as the filed is submitted to remote API.
For normal fields i do <?php echo $form->field($model, 'name')->textInput(['name' => 'name']) ?>
In the options you could assign an your name value
<?php echo $form->field($model, 'body',
[ 'options' => [ 'name' => 'your_name']])->widget(
\yii\imperavi\Widget::className(),
[
'plugins' => ['fontcolor', 'video'],
'options'=>[
'minHeight'=>400,
'maxHeight'=>400,
'buttonSource'=>true,
//'imageUpload'=>Yii::$app->urlManager->createUrl(['/file-storage/upload-imperavi'])
]
]
) ?>
Thank you guys this worked.
<?php
echo yii\imperavi\Widget::widget([
// You can either use it for model attribute
'model' => $model,
'attribute' => 'body',
// or just for input field
//'name' => 'body',
'htmlOptions'=>[
'name'=>'body',
],
// Some options, see http://imperavi.com/redactor/docs/
'options' => [
'toolbar' => false,
],
]);
?>
and this also
<?php echo $form->field($model, 'body',
[ 'options' => [ 'name' => 'body']])->widget(
\yii\imperavi\Widget::className(),
[
'plugins' => ['fontcolor', 'video'],
'htmlOptions'=>['name'=>'body'],
'options'=>[
'minHeight'=>400,
'maxHeight'=>400,
'buttonSource'=>true,
//'imageUpload'=>Yii::$app->urlManager->createUrl(['/file-storage/upload-imperavi'])
]
]);?>

The upload variable is empty in yii2

i want add uploadFile to: https://github.com/thyseus/yii2-message
i added public $file2 in Message.php in model
and this is my rules in model:
public function rules()
{
return [
[['title'], 'required'],
[['file2'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg'],
[['title', 'message', 'context'], 'string'],
[['title'], 'string', 'max' => 255],
[['to'], IgnoreListValidator::class],
[['to'], 'exist',
'targetClass' => Yii::$app->getModule('message')->userModelClass,
'targetAttribute' => 'id',
'message' => Yii::t('app', 'Recipient has not been found'),
],
[['to'], 'required', 'when' => function ($model)
{
return $model->status != Message::STATUS_SIGNATURE && $model->status != Message::STATUS_DRAFT;
}],
];
}
and this is my view:
<?= $form->field($model, 'message')->textarea(['rows' => 6]) ?>
<?php
echo $form->field($model, 'file2')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]);
// With model & without ActiveForm
echo '<label class="control-label">Add Attachments</label>';
echo FileInput::widget([
'model' => $model,
'attribute' => 'file2',
'options' => ['multiple' => true]
]);
?>
and this is my sendMessage Function
$model = new Message();
$model->attributes = $attributes;
var_dump($attributes);
die;
why after upload file my result is this?
array(4) { ["to"]=> array(1) { [0]=> string(2) "65" } ["title"]=> string(3) "asd" ["message"]=> string(30) "asd . " ["file2"]=> string(0) "" }
file2 is empty !
When setting up the form, you need to mention as multipart/form-data. check below example.
<?php
use yii\widgets\ActiveForm;
?>
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]) ?>
<?= $form->field($model, 'file2')->fileInput() ?>
<button>Submit</button>
<?php ActiveForm::end() ?>

How display kartik\Select2 in modal window use renderAjax

I use http://demos.krajee.com/widget-details/select2#usage-tags
controller
public function actionTagsForm()
{
$method = Yii::$app->request->isAjax ? 'renderAjax' : 'render';
$model = new UserTagsForm();
return $this->$method('tagsForm', ['model' => $model]);
}
views/layouts/main.php has code modal window
<?php
yii\bootstrap\Modal::begin([
'header' => '<div id="modalHeader"></div>',
'id' => 'modal',
'size' => 'modal-lg',
'options' => [
'tabindex' => false
],
]);
echo "<div id='modalContent'></div>";
yii\bootstrap\Modal::end();
?>
view
$data = [
"red" => "red",
"green" => "green",
"blue" => "blue",
"orange" => "orange",
"white" => "white",
"black" => "black",
"purple" => "purple",
"cyan" => "cyan",
"teal" => "teal"
]; ?>
<div class="image-tags-index">
<?php $form = ActiveForm::begin();?>
<?php echo $form->field($model, 'image_tags')->widget( Select2::classname(),[
'data' => $data,
'options' => ['placeholder' => 'Select a state ...'],
'pluginOptions' => [
'allowClear' => true
],
])->label('Tag Multiple');
?>
</div>
error
VM314:2 Uncaught ReferenceError: select2_3f25e3ac is not defined
at eval (eval at globalEval (jquery.js:343), :2:56)
at eval ()
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at jQuery.fn.init. (jquery.js:5525)
at access (jquery.js:3614)
at jQuery.fn.init.html (jquery.js:5492)
at Object. (jquery.js:9436)
at fire (jquery.js:3187)
This problem has been solved in the https://github.com/kartik-v/yii2-widget-select2/issues/211

Yii2 select2 ajax dropdown loading

I am using two select2 ajax loading dropdown list using Yii2 kartik widget. I need to change selection of second dropdown while changing selection of first dropdown.
First Dropdown
<?php
$qtnno = '';
$qtn = ServiceQuotation::find()->where(['UDNO' => $model->QTN_UDNO])->one();
if($qtn != null) $qtnno = $qtn->UDNO;
echo $form->field($model, 'QTN_UDNO')->widget(Select2::classname(), [
'initValueText' => $qtnno, // set the initial display text
'options' => ['placeholder' => 'Search for a Quotation ...',
'onchange'=>'
$.getJSON( "'.Url::toRoute('getqtndetails').'", { id: $("#servicejobcard-qtn_udno").val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'QTNNO').'" ).val( data.qtnno );
$( "#'.Html::getInputId($model, 'QTNDATE').'" ).val( data.qtndate );
$( "#'.Html::getInputId($model, 'PCODE').'" ).select2({ data: [{id: data.pcode, text: data.pname}]});;
$( "#'.Html::getInputId($model, 'PCODE').'" ).select2("val",data.pcode);
$( "#'.Html::getInputId($model, 'PROJECTNAME').'" ).val( data.projectname );
}
);'
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $urlQtn,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(data) { return data.text; }'),
'templateSelection' => new JsExpression('function (data) { return data.text; }'),
],
]);
?>
Second Drop Down
<?php
$cusName = empty($model->PCODE) ? '' : Customer::findOne($model->PCODE)->PNAME;
echo $form->field($model, 'PCODE')->widget(Select2::classname(), [
'initValueText' => $cusName, // set the initial display text
'options' => ['placeholder' => 'Search for a Customer ...',
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(party) { return party.text; }'),
'templateSelection' => new JsExpression('function (party) { return party.text; }'),
],
]);
?>
Using the above code i'm able to change the selection in second dropdown. But after the change, i'm not able to make selection in second dropdown.
Please help...
Try to use onchange event this way:
[
'options' => [],
// other settings
'pluginEvents' => [
'change' => "function() { alert('change'); }",
]
]
You can find additional information on that page http://demos.krajee.com/widget-details/select2
If you are not restricted to using only Select2 widget, I would suggest you use the Kartik V's DepDrop Widget specifically created for dependent drop-downs.
Since you have not given a lot of context to what your code is actually doing, I am giving a simple 2 level dependency example (slightly modified version of example given in Kartik V's depdrop widget page).
/*
* 2-level dependency example
*/
// THE VIEW
use kartik\widgets\DepDrop;
// Parent
echo $form->field($model, 'cat')->dropDownList($catList, ['id'=>'cat-id']);
// Dependent Dropdown (Child)
echo $form->field($model, 'subcat')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['cat-id'],
'placeholder'=>'Select...',
'url'=>Url::to(['/site/subcat'])
]
]);
// THE SITE CONTROLLER (/site/subcat)
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = self::getSubCatList($cat_id);
// the getSubCatList function will query the database based on the
// cat_id and return an array like below:
// [
// ['id'=>'<sub-cat-id-1>', 'name'=>'<sub-cat-name1>'],
// ['id'=>'<sub-cat_id_2>', 'name'=>'<sub-cat-name2>']
// ]
echo Json::encode(['output'=>$out, 'selected'=>'']);
return;
}
}
echo Json::encode(['output'=>'', 'selected'=>'']);
}
The above code can be customized to your requirements.
Here is the link for more details: http://demos.krajee.com/widget-details/depdrop
you can add this kind of query to make the job.
$cusname=QtnUdno::find()->select('PCODE')->where(['UDNO'=>$model->QTN_UDNO])->one();