Yii2 - Dynamic Form with a single model - yii2

I have always worked with Dynamic Form that saved in multiple models, especially wbraganca. However, I want to create a Dynamic Form whereby everything will be saved on the same Model Class, CentreProgramme. When the Add button is clicked, Dropdownlist with attribute Programme_id will be created.
How do I achieve this.
I used the code shown below, but the Dropdown is not wide enough to accommodate on the data. When I select all from the dropdown, it spreads accross the dropdown because the data is too large. Thanks
I have this Model Class
CentreProgramme
public function attributeLabels()
{
return [
'id' => Yii::t('centre', 'ID'),
'state_office_id' => Yii::t('centre', 'State Office'),
'study_centre_id' => Yii::t('centre', 'Study Centre'),
'programme_id' => Yii::t('centre', 'Programme'),
];
}
Controller
public function actionCreate()
{
$model = new StudyCentreProgramme();
if ($model->load(Yii::$app->request->post()) && isset($_POST['StudyCentreProgramme'])) {
$model->attributes = $_POST['StudyCentreProgramme'];
for($i=0;$i<count($_REQUEST['StudyCentreProgramme']['programme_id']);$i++) :
$model->id = NULL;
$model->isNewRecord = true;
$model->programme_id = $_POST['StudyCentreProgramme']['programme_id'][$i];
$model->state_office_id = $_POST['StudyCentreProgramme']['state_office_id'];
$model->study_centre_id = $_POST['StudyCentreProgramme']['study_centre_id'];
if($model->save()) {
Yii::$app->session->setFlash('green-'.$i, '<i class="fa fa-info-circle"></i> <b>Study Centre Programme: </b> is created successfully');
} else {
Yii::$app->session->setFlash('red-'.$i, '<i class="fa fa-warning"></i><b>Study Centre Programme: </b> has already been taken.');
}
endfor;
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
View
<?php $form = ActiveForm::begin([
'id' => 'study-centre-programme-form',
'fieldConfig' => [
'template' => "{label}{input}{error}",
],
]); ?>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'state_office_id')->dropDownList(ArrayHelper::map(\common\models\StateOffice::find()->where(['is_status' => 0])->all(),'id','state_name'),
[
'prompt'=>Yii::t('app', '--- Select State Officee ---'),
'onchange'=>'
$.get( "'.Url::toRoute('dependent/getprogrammestudycentre').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($model, 'state_office_id').'" ).html( data );
}
);'
]
); ?>
</div>
<div class="col-xs-12 col-sm-6 col-lg-6">
<?= $form->field($model, 'state_office_id')->dropDownList([''=>Yii::t('app', '--- Select Study Centre ---')]); ?>
</div>
<div class="col-xs-12 col-sm-12 col-lg-12">
<?php
if(Yii::$app->controller->action->id === 'create' ) {
echo $form->field($model, 'programme_id[]')->dropDownList(ArrayHelper::map(common\models\Programme::find()->where(['is_status' => 0])->all(),'id','programme_name'),['multiple' => "multiple", 'class'=>'form-control', 'placeholder' => $model->getAttributeLabel('programme_id')]);
} else {
echo $form->field($model, 'programme_id')->dropDownList(ArrayHelper::map(common\models\Programme::find()->where(['is_status' => 0])->all(),'id','programme_name'),['class'=>'form-control', 'placeholder' => $model->getAttributeLabel('programme_id')]);
}
?>
</div>
<div class="form-group col-xs-12 col-sm-6 col-lg-4 no-padding jkkesrmsArLangCss">
<div class="col-xs-6">
<?= Html::submitButton($model->isNewRecord ? Yii::t('centre', 'Create') : Yii::t('centre', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-block btn-success' : 'btn btn-block btn-info']) ?>
</div>
<div class="col-xs-6">
<?= Html::a(Yii::t('centre', 'Cancel'), ['index'], ['class' => 'btn btn-default btn-block']); ?>
</div>
</div>
<?php ActiveForm::end(); ?>
[

Related

Yii2 Pjax reloads the page even with renderPartial

I am sending Pjax request which reloads the whole page even when I am using renderPartial. The pjax container is #promo-products than why it reloads the whole page not only fill the container with the desired results ? If I var_dump($child_products);die; it shows the result right in the container but without die it reloads the page. Also tried to render a partial view ( like _children lets say ) but the result was the same. What is my mistake?
Controller:
public function actionCreate()
{
$model = new Promotion();
$products = [];
$success = null;
$child_products = [];
if(Yii::$app->request->isPjax){
$parent_id = Yii::$app->request->get('parent_id');
if($parent_id){
$parent_children = ProductChild::find()->where(['id_in' => $parent_id])->all();
foreach ($parent_children as $child){
$child_products[$child['id']][] = $child;
}
}
}
if (!Yii::$app->request->isPjax && $model->load(Yii::$app->request->post())) {
$transaction = Yii::$app->db->beginTransaction();
try{
if($model->save()){
//save products
$model->saveProducts();
$transaction->commit();
return $this->redirect(['index', 'success' => 1]);
} else {
throw new \Exception("Some error occurred.");
}
}catch (\Exception $e){
$success = 3;
$model = new Promotion();
$transaction->rollBack();
}
}
if(Yii::$app->request->isPjax){
return $this->renderPartial('create', [
'child_products' => $child_products,
]);
}
return $this->render('create', [
'model' => $model,
'products' => $products,
'success' => $success,
'child_products' => $child_products,
]);
}
And my view:
<?php
use yii\widgets\ActiveForm;
use backend\helpers\Header;
use kartik\select2\Select2;
use yii\web\JsExpression;
use backend\helpers\CGrowl;
\backend\assets\JquerySteps::register($this);
\backend\assets\DateTimePickerAsset::register($this);
/* #var $this yii\web\View */
/* #var $model backend\models\Contact */
/* #var $form yii\widgets\ActiveForm */
$this->registerJs("
$('#promotion-start_date').bootstrapMaterialDatePicker({ format: 'YYYY-MM-DD HH:mm:ss' });
$('#promotion-end_date').bootstrapMaterialDatePicker({ format: 'YYYY-MM-DD HH:mm:ss' });
",
\yii\web\View::POS_LOAD,
'datetime-picker-init'
);
if (isset($success)) {
echo CGrowl::setFormResult((int)$success, $this);
}
?>
<div class="row page-titles" style="background-image: url('<?= Yii::getAlias('#backend-image') ?>/theme/images/heading-title-bg.jpg')">
<div class="col-md-12">
<h4 class="text-white"><?= Yii::t('app', 'Promotion') ?></h4>
</div>
<div class="col-md-6">
<?= Header::renderBreadcrumbs($this) ?>
</div>
</div>
<div class="row" id="validation">
<div class="col-12">
<div class="card wizard-content">
<div class="card-body">
<div class="panel-body">
<?php $form = ActiveForm::begin([
'options' => [
'class' => 'validation-wizard wizard-circle'
],
]); ?>
<h6><?= Yii::t('app', 'Main info') ?></h6>
<section>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'type')->widget(Select2::class, [
'data' => [
1 => Yii::t('app', 'Percentage'),
2 => Yii::t('app', 'Price'),
],
'options' => [
'placeholder' => Yii::t('app', 'Type')
],
'pluginOptions' => [
'allowClear' => true
]
]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'value')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'start_date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'end_date')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($model, 'products')->widget(Select2::class, [
'initValueText' => $products,
'options' => [
'multiple' => true
],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 3,
'language' => [
'errorLoading' => new JsExpression("function(){return 'Waiting for results ...'; }"),
],
'ajax' => [
'url' => \yii\helpers\Url::to(['async/products']),
'dataType' => 'json',
'data' => new JsExpression("function(params){return {q:params.term}; }")
],
'escapeMarkup' => new JsExpression("function(markup){return markup;}"),
'templateResult' => new JsExpression("function(city){return city.text;}"),
'templateSelection' => new JsExpression("function(city){return city.text;}")
],
'pluginEvents' => [
'select2:select' => "function(){
let url = location.href.split('?')[0]
$.pjax.defaults.timeout = false
$.pjax({
url: url,
data: {
parent_id: this.value
},
container: '#promo-products'
})
}"
]
]) ?>
</div>
<div class="col-sm-8">
<label for=""><?= Yii::t('app', 'Varieties')?></label>
<div class="table-responsive">
<table>
<?php \yii\widgets\Pjax::begin(['id' => 'promo-products']) ?>
<tbody>
<?php
foreach ($child_products as $child){
echo $child->id;
}
?>
</tbody>
<?php \yii\widgets\Pjax::end() ?>
</table>
</div>
</div>
<div class="col-sm-12">
</div>
</div>
</section>
<?php ActiveForm::end(); ?>
</div>
</div>
</div>
</div>
</div>

Insert multiple records of a same table Yii2

I want to insert same record in one table. I have only one input array in the below form but i want to save multiple time record for label input array.
my form is
<div class="surveys-questions-form">
<?php $form = ActiveForm::begin(); ?>
<?php
if(isset($_GET['option_id']) and $_GET['option_id'] > 0)
$id= $_GET['option_id'];
else
$id= $model->option_id;
echo $form->field($model, 'question_id')->hiddenInput(['value' => $id])->label(false);
?>
<div class="col-md-6">
<div id="question_wrapper">
<?= $form->field($model, 'type')->dropDownList([ 'text' => 'Text', 'numbers' => 'Numbers', 'date' => 'Date', 'texarea' => 'Texarea', 'checkbox' => 'Checkbox', 'radio' => 'Radio', 'rating' => 'Rating', ], ['prompt' => '']) ?>
<div id="add_more_field">
<?= $form->field($model, 'label[]')->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?php
echo Html::a('Add more', 'javascript:void(0);', [
'id' => 'surveys-questions-new-button',
'class' => 'pull-right btn btn-primary btn-xs'
])
?>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
and controller
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}
Give me the following error when i try to submit form.
Label must be a string.
My $_POST array
Array
(
[_csrf-backend] => LXBhajI3YVpOIikeRWYHYkNCAD4Kb1ZrQzwER21GL2MdCTgkWm5ZDQ==
[QuestionsOptions] => Array
(
[question_id] => 47
[type] => numbers
[label] => Array
(
[0] => Label1
[1] => Label2
[2] => Labe3
)
)
)
If you want to save multiple record use loop i suggest you to use foreach loop it is best
public function actionCreate()
{
$model = new QuestionsOptions();
if ($model->load(Yii::$app->request->post())) {
if(sizeof(array_filter($_POST['QuestionsOptions']['label'])) > 0){
foreach($_POST['QuestionsOptions']['label'] as $key => $row){
$model->setIsNewRecord(true);
$model->id = null;
$model->label = $row;
$model->save();
}
}
return $this->redirect(['view', 'id' => $model->option_id]);
} else {
return $this->renderAjax('create', [
'model' => $model,
]);
}
}

yii2 dynamic form inserting data in one model only

I'm trying to incorporate wbraganca dynamic form in yii2. But it's inserting data in only bills table(equivalent to the customer table) but not in productsales table(equivalent to address table). I'm not getting where the error is. There's no error in the console. After hitting the create button the page goes blank with a white screen. I can see data inserted in the bills table but not in productsales table.
_form.php in bills -
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use kartik\form\ActiveForm;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use yii\helpers\Json;
use yii\web\View;
use frontend\modules\invoice\models\Parties;
use frontend\modules\invoice\models\Productbatch;
use frontend\modules\invoice\models\Year;
use frontend\modules\invoice\models\Console;
use wbraganca\dynamicform\DynamicFormWidget;
use kartik\depdrop\DepDrop;
/* #var $this yii\web\View */
/* #var $model frontend\modules\invoice\models\Bills */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="bills-form">
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
]); ?>
<div class="row">
<div class="form-group">
<div class="col-xs-9 col-sm-9 col-lg-9">
<?= $form->field($model, 'bills_partyname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Parties::find()->orderBy(['parties_partyname' => SORT_ASC,])->all(),'parties_partyname','partyDetails'),
'language' => 'en',
'options' => ['placeholder' => 'Select Party Name', 'id' => 'partyid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'transport')->textInput(['maxlength' => true]) ?>
</div>
</div>
<div class="form-group">
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'bills_year')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Year::find()->orderBy(['yid' => SORT_DESC,])->all(),'year_year','year_year'),
'language' => 'en',
'options' => ['placeholder' => 'Select Year', 'id' => 'yearid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'console')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Console::find()->orderBy(['consoleid' => SORT_ASC,])->all(),'console','console'),
'language' => 'en',
'options' => ['placeholder' => 'Select Console','id' => 'consoleid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'billno')->textInput(['maxlength' => true,'readOnly'=>true]) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'billdate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
</div>
</div>
<?= $form->field($model, 'bills_ebillid')->textInput()->hiddenInput()->label(false) ?>
<?= $form->field($model, 'num')->textInput()->hiddenInput()->label(false) ?>
</div>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Products</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' => 20, // 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' => $modelsProductsales[0],
'formId' => 'dynamic-form',
'formFields' => [
//'itemid',
'productname',
//'batchno',
// 'expdate',
// 'mrp',
// 'rate',
// 'qty',
// 'free',
// 'total',
// 'discount',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsProductsales as $i => $modelsProductsales): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Products</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 (! $modelsProductsales->isNewRecord) {
echo Html::activeHiddenInput($modelsProductsales, "[{$i}]id");
}
?>
<div class="row-fluid">
<div class="form-group">
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Productname']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<?= $form->field($modelsProductsales, "[{$i}]batchno")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Batchno']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding" >
<?= $form->field($modelsProductsales, "[{$i}]expdate")->label(false)->textInput(['maxlength' => true,'placeholder' => 'ExpDate']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<?= $form->field($modelsProductsales, "[{$i}]mrp")->label(false)->textInput(['maxlength' => true,'placeholder' => 'MRP']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<?= $form->field($modelsProductsales, "[{$i}]rate")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Rate']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<?= $form->field($modelsProductsales, "[{$i}]qty")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Qty']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<?= $form->field($modelsProductsales, "[{$i}]free")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Free']) ?>
</div>
<div class="col-xs-1 col-sm-1 col-lg-1 nopadding">
<?= $form->field($modelsProductsales, "[{$i}]discount")->label(false)->textInput(['maxlength' => true,'placeholder' => 'Discount']) ?>
</div>
</div>
<?= $form->field($modelsProductsales, "[{$i}]itemid")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]total")->textInput(['maxlength' => true]) ?>
</div><!-- .row -->
</div>
</div><!-- item panel default -->
<?php endforeach; ?>
</div><!-- container item -->
<?php DynamicFormWidget::end(); ?>
</div><!-- panel body -->
</div><!-- panel default -->
</div><!-- outer row -->
<?= $form->field($model, 'billamount')->textInput() ?>
<?= $form->field($model, 'overdue')->textInput() ?>
<?= $form->field($model, 'cst')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'wbst')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'caseno')->textInput() ?>
<?= $form->field($model, 'amount')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'discount')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'tot')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'surcharge')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'total')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'tax')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'mrpvalue')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'cstpercent')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'wbstpercent')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'surpercent')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'totpercent')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'transport')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
/* start getting the transportdata */
$script = <<< JS
$('#partyid').change(function(){
var partyid = $(this).val();
$.get('index.php?r=invoice/bills/get-for-party',{ partyid : partyid }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#bills-transport').attr('value',data.transport);
});
});
JS;
$this->registerJs($script);
/* end getting the transportdata */
?>
<?php
/* start getting the ebilid */
$script = <<<EOD
$(window).load(function(){
$.get('index.php?r=invoice/bills/get-for-ebillid',{ ebillid : 1 }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#bills-bills_ebillid').attr('value',data.ebillid);
}
);
});
EOD;
$this->registerJs($script);
/*end getting the ebillid */
?>
<?php
/* start getting the num */
$script = <<< JS
$(function(){
$('#yearid').change(function(){
getNum();
});
$('#consoleid').change(function(){
getNum();
});
var yearid = $(this).val();
var consoleid = $(this).val();
var getNum = function(){
var yearid = String($('#yearid').val());
var consoleid = String($('#consoleid').val());
$.get('index.php?r=invoice/bills/get-for-num',{ yearid : yearid, consoleid : consoleid }, function(data){
//alert(data);
var data = $.parseJSON(data);
var getNum = data;
$('#bills-num').val(getNum["num"]);
});
} ;
});
JS;
$this->registerJs($script);
/* end getting the num */
?>
<?php
/* start getting the billno */
$script = <<< JS
$(function(){
$('#yearid').change(function(){
getBillno();
});
$('#consoleid').change(function(){
getBillno();
});
var yearid = $(this).val();
var consoleid = $(this).val();
var getBillno = function(){
var yearid = String($('#yearid').val());
var consoleid = String($('#consoleid').val());
$.get('index.php?r=invoice/bills/get-for-billno',{ yearid : yearid, consoleid : consoleid }, function(data){
//alert(data);
var data = $.parseJSON(data);
var getBillno = data;
$('#bills-billno').val(getBillno["billno"]);
});
} ;
});
JS;
$this->registerJs($script);
/* end getting the billno */
?>
BillsController
<?php
namespace frontend\modules\invoice\controllers;
use Yii;
use frontend\modules\invoice\models\Bills;
use frontend\modules\invoice\models\BillsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use frontend\modules\invoice\models\Parties;
use frontend\modules\invoice\models\Productsales;
use frontend\modules\invoice\models\Productbatch;
use frontend\modules\invoice\models\Model;
use yii\helpers\Json;
/**
* BillsController implements the CRUD actions for Bills model.
*/
class BillsController extends Controller
{
/**
* #inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Bills models.
* #return mixed
*/
public function actionIndex()
{
$searchModel = new BillsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Bills model.
* #param string $id
* #return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Bills model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
public function actionCreate()
{
$model = new Bills();
$modelsProductsales = [new Productsales];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$modelsProductsales = Model::createMultiple(Productsales::classname());
Model::loadMultiple($modelsProductsales, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsProductsales) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsProductsales as $modelProductsales) {
$modelProductsales->productsales_ebillid = $model->bills_ebillid;
$modelProductsales->year = $model->bills_year;
$modelProductsales->console = $model->console;
$modelProductsales->billno = $model->billno;
$modelProductsales->billdate = $model->billdate;
$modelProductsales->productsales_partyname = $model->bills_partyname;
if (! ($flag = $modelProductsales->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
//return $this->redirect(['view', 'id' => $model->billid]);
else {
return $this->render('create', [
'model' => $model,
'modelsProductsales' => (empty($modelsProductsales)) ? [new Productsales] : $modelsProductsales
]);
}
}
/**
* Updates an existing Bills model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param string $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->billid]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
/**
* Deletes an existing Bills model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param string $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
public function actionGetForParty($partyid)
{
$party = Parties::find()->where(['parties_partyname'=>$partyid])->asArray()->one();
//$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1);
echo Json::encode($party);
}
public function actionGetForEbillid($ebillid)
{
$ebillidvar = Bills::find()->select('(max(bills_ebillid) + 1) as ebillid')->asArray()->one();
echo Json::encode($ebillidvar);
}
public function actionGetForNum($yearid , $consoleid)
{
$num = Bills::find()->select('(max(num) + 1) as num')->where(['bills_year'=>$yearid])->andWhere(['console'=>$consoleid])->asArray()->one();
echo Json::encode($num);
}
public function actionGetForItemid($productid , $batchid)
{
$item = Productbatch::find()->select('max(itemid) as itemid')->where(['productname'=>$productid])->andWhere(['batchno'=>$batchid])->asArray()->one();
echo Json::encode($item);
}
public function actionGetForBillno($yearid , $consoleid)
{
if($consoleid == 'GM1' || $consoleid == 'GM2'){
$num = Bills::find()->select(['concat("GM/",(max(num) + 1)) as billno'])->where(['bills_year'=>$yearid])->andWhere(['console'=>$consoleid])->asArray()->one();
echo Json::encode($num);
}elseif($consoleid == 'SM1' || $consoleid == 'SM2'){
$num = Bills::find()->select(['concat("SM/",(max(num) + 1)) as billno'])->where(['bills_year'=>$yearid])->andWhere(['console'=>$consoleid])->asArray()->one();
echo Json::encode($num);
}elseif($consoleid == 'CN'){
$num = Bills::find()->select(['concat("CM/",(max(num) + 1)) as billno'])->where(['bills_year'=>$yearid])->andWhere(['console'=>$consoleid])->asArray()->one();
echo Json::encode($num);
}
}
public function actionSubcat() {
$out = [];
if (isset($_POST['depdrop_parents'])) {
$parents = $_POST['depdrop_parents'];
if ($parents != null) {
$cat_id = $parents[0];
$out = Productbatch::getBatchNo($cat_id);
echo Json::encode($out);
// 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'=>'']);
}
/**
* Finds the Bills model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param string $id
* #return Bills the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Bills::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Create.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model frontend\modules\invoice\models\Bills */
$this->title = 'Create Bills';
$this->params['breadcrumbs'][] = ['label' => 'Bills', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="bills-create">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'modelsProductsales' => $modelsProductsales,
]) ?>
</div>
Model.php
<?php
namespace frontend\modules\invoice\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* #param string $modelClass
* #param array $multipleModels
* #return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}

How to reload pjax div in modal window in yii2

I have used modal for viewing comments list, with modal having an update button and a textbox.
When a user enters some text in the text box and click update button i want the comments list div to be reloaded without the whole page being reloaded or the modal being closed or hided.
I have already read
How to update widget with pjax in modal window in yii2
que. but still not getting solution.
My code is
Registered Js and view file
$this->registerJs("
$(function() {
$('#replayMeg').on('beforeSubmit', function(event, jqXHR, settings) {
var comment = $('#".Html::getInputId($modelReply, 'hdr_comments')."').val();
var ticketId = $model->hdt_id;
$.ajax({
url: '".Url::to(['helpdesk-replies/create'])."',
type: 'post',
data: { replyMsg : comment, ticketId : ticketId},
beforeSend: function() {
if($('#".Html::getInputId($modelReply, 'hdr_comments')."').val() == '')
{
$('.field-helpdeskreplies-hdr_comments').addClass('form-group field-helpdeskreplies-hdr_comments required has-error');
$('.help-block').html('Reply cannot be blank.');
return false;
}
},
success: function(data) {
//$.pjax.reload({container:'#update_replyBox'});
}
});
return false;
})
});
");
<?php yii\widgets\Pjax::begin(['id' => 'update_replyBox']); ?>
<div class="modal-body">
<div class="box-tools pull-right">
<?= $actionBtn; ?>
</div>
</div>
<div class="panel panel-info">
<div class="panel-heading colorchangeheader left-align">
<i class="fa fa-users fa-fw"></i> <?= $model->getUserName($cData['hdr_replay_user_id']); ?> <span class="mobilebreakpoint"><i class="fa fa-clock-o fa-fw"></i><?= Yii::$app->formatter->asDate($cData['created_at']); ?> # <?= Yii::$app->formatter->asTime($cData['created_at']); ?></span>
</div>
<div id="rp8" class="panel-body">
<?= $cData['hdr_comments'] ?>
</div>
</div>
<?php $form = ActiveForm::begin(['id' => 'replayMeg']); ?>
<div class="box-body">
<div class='row'>
<div class='col-sm-12'>
<?=
$form->field($modelReply, 'hdr_comments')->widget(RemainingCharacters::className(), [
'type' => RemainingCharacters::INPUT_TEXTAREA,
'name' => 'message_body',
'id' => 'message_body-textarea',
'text' => Yii::t('app', '{n} Characters Remaining'),
'label' => [
'tag' => 'p',
'id' => 'my-counter',
'class' => 'counter text-aqua',
'invalidClass' => 'error'
],
'options' => [
'rows' => '3',
'class' => 'form-control replyTextArea',
'maxlength' => 200,
'placeholder' => Yii::t('app', 'Write something'),
]
]);
?>
</div>
</div>
<!--/div>
<div class="box-footer"-->
<?= Html::button('<i class="fa fa-reply"></i> '.Yii::t('comm', 'Reply'), ['class' => 'btn btn-info btn-create submit', 'type' => 'submit']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
Please try to set backdrop false in the modal
'clientOptions' => ['backdrop' => false]
or
Set data-pjax true in your active form
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>
For more details http://www.yiiframework.com/wiki/772/pjax-on-activeform-and-gridview-yii2/
For more options on Modal Refer

Yii2 Pjax on ActiveForm and GridView [ Got it Working]

I have a gridview
<?php Pjax::begin(['id' => 'members']) ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'columns' => [
['header'=>'Remove Member',
'value'=> function($data)
{
return Html::a(Yii::t('app', ' {modelClass}', [
'modelClass' =>'',
]), ['members/stl_remove','id'=>$data->id],
['class' => 'btn btn-link fa fa-times fa-2x pop']
);
},
'format' => 'raw'
],
['class' => 'yii\grid\ActionColumn','template'=>'{update}'],
],
]); ?>
<?php Pjax::end() ?>
when i click on the Remove members link a modal popsup (delete.php)
<?php Pjax::begin(['id' => 'delete_members']) ?>
<?php $form = ActiveForm::begin(['options' => ['data-pjax' => true ]]); ?>
<div class="row">
<div class="col-md-5">
<?php echo $form->field($model, 'remarks')->dropDownList(['death' => 'Death',
'marriage' => 'Marriage', 'house_shift' => 'House Shift'],['prompt'=>'Select'])
->label("Reason For Removal"); ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Remove') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
Now these are my controller code
[code]
public function actionStl_remove($id,$ajax=0)
{
$model = $this->findModel($id);
$model_delete = new Members();
$model->scenario = "remove";
if ($model_delete->load(Yii::$app->request->post()))
{
$model->remarks = $model_delete->remarks;
$model->status = 1;
$model->save();
// $model = new Members();
// return $this->redirect(['index']);
}
else
{
return $this->renderAjax('delete', [
'model' => $model_delete,
'id' => $id,
]);
}
}
I am not able to get data loaded into gridview. I click on the link modal popsup then i submit after that i go on to the index page and the page reloads
This is how i got it working. In delete.php i made following changes.
<?php $form = ActiveForm::begin([
'options' => ['data-pjax' => true,
'id'=> 'dynamic-form111',
// 'validationUrl' => 'validation-rul'
]]); ?>
<div class="row">
<div class="col-md-5">
<?php echo $form->field($model, 'remarks')->dropDownList(['death' => 'Death',
'marriage' => 'Marriage', 'house_shift' => 'House Shift'],['prompt'=>'Select'])
->label("Reason For Removal"); ?>
</div>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? Yii::t('app', 'Remove') : Yii::t('app', 'Update'), ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
basically i gave an id to the from dynamic-form111.
Then in index.php along with gridview in pjax i added the below code
<?php
$this->registerJs(
'jQuery(document).ready(function($){
$(document).ready(function () {
$("body").on("beforeSubmit", "form#dynamic-form111", function () {
var form = $(this);
// return false if form still have some validation errors
if (form.find(".has-error").length)
{
return false;
}
// submit form
$.ajax({
url : form.attr("action"),
type : "post",
data : form.serialize(),
success: function (response)
{
$("#ajaxModal").modal("toggle");
$.pjax.reload({container:"#countries"}); //for pjax update
},
error : function ()
{
console.log("internal server error");
}
});
return false;
});
});
});'
);
?>
which via ajax check if delete.php has been submitted successfully if yes then reloads gridview using pjax and closes modal.