yii2 - multiple rows load into same table from one form - yii2

I am trying to save a schedule of working days on a table multiple rows at once...
I am doing this wrong, still giving me errors.
I have seen tabular inputs from others, but can't get this right.
I really need some other eyes on it.
I have a similar problem as https://phppedia.com/en/knowledge-base/32481399/yii2-insert-multiple-records-of-a-same-table
model:
public
function rules()
{
return [
['store_id', 'string'],
['day', 'string'],
['start_hour', 'string'],
['end_hour', 'string'],
['holiday','boolean'],
];
}
controler:
public function actionCreate()
{
$count = count(Yii::$app->request->post('Openhour', []));
$model = [new Openhours()];
for ($i = 1; $i < $count; $i++) {
$model[] = new Openhours();
}
if ($model->loadMultiple($model, Yii::$app->request->post())) {
foreach ($model as $model) {
$model->save(false);
}
}
return $this->render('create', ['model' => $model,]);
}
_form
<?php $stores = Stores::getAll() ?>
<?php foreach ($stores as $store): ?>
<?php if ($store->id !== 0): ?>
<?php $listData[$store->id] = [$store->id => $store->title]; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true, 'options' => ['class' => 'model-form'],]); ?>
<?php foreach ($model as $index => $model): ?>
<div class="row row-cols-3">
<div class="col">
<h5>
<?php if ($store->title === Yii::$app->user->identity->username) : ?>
<?= $form->field($model, '[$index]store_id')->hiddenInput(['value' => $store->title])->label($store->title) ?>
<?php else: ?>
<?= $form->field($model, '[$index]store_id')->dropDownList($listData, ['prompt' => 'Select...']); ?>
<?php endif; ?>
</h5>
</div>
<div class="col">Opening</div>
<div class="col">Close</div>
</div>
<?php $days = Storedays::getAll() ?>
<?php foreach ($days as $day): ?>
<div class="row row-cols-3">
<div class="col">
<div class="row justify-content-between">
<div class="col">
<h6><?= $day->name ?></h6>
<?= $form->field($model, '[$index]day')->hiddenInput(['value' => $day->name, 'id' => 'day' . $day->id])->label(false) ?>
</div>
<div class="col">
<?= $form->field($model, '[$index]holiday')->checkbox(['selected' => $model->holiday, 'id' => 'holiday' . $day->id])->label(false) ?>
</div>
</div>
</div>
<div class="col">
<?= $form->field($model, '[$index]start_hour')->Input('text')->widget(TimePicker::class, ['options' => ['id' => 'start_hour' . $day->id], 'pluginOptions' => ['maxHours' => '8', 'template' => 'dropdown', 'showSeconds' => false, 'showMeridian' => false, 'minuteStep' => 15,]])->label(false) ?>
</div>
<div class="col">
<?= $form->field($model, '[$index]end_hour')->Input('text')->widget(TimePicker::class, ['options' => ['id' => 'end_hour' . $day->id], 'pluginOptions' => ['maxHours' => '8', 'template' => 'dropdown', 'showSeconds' => false, 'showMeridian' => false, 'minuteStep' => 15,]])->label(false) ?>
</div>
</div>
<?php endforeach; ?>
<?php if (IS_ROOT) : ?><?= $form->field($model, '[$index]slug') ?><?php endif; ?>
<?= Html::submitButton('save', ['class' => 'btn btn-primary']) ?>
<hr class="mb-3">
<?php endforeach; ?>
<?php ActiveForm::end(); ?>

First you have an array of objects and you must use plural name instead.
So model become models.
Second you must use functions for loading multiple models from request Model::loadMultiple($models) and for validate multiple models Model::validateMultiple($models).
Now in your controller:
public function actionCreate()
{
$count = count(Yii::$app->request->post('Openhour', []));
$models = [new Openhours()];
for ($i = 1; $i < $count; $i++) {
$models[] = new Openhours();
}
if (Model::loadMultiple($models, Yii::$app->request->post()) && Model::validateMultiple($models)) {
foreach ($models as $model) {
$model->save(false);
}
}
return $this->render('create', ['models' => $models]);
}
Now in your _form.php change the line:
<?php foreach ($model as $index => $model): ?>
To:
<?php foreach ($models as $index => $model): ?>

Related

Catch button in controller

I have this form in view
<?php
$form = ActiveForm::begin();
$items = [201 => 'Тест', 202 => 'Тест2'];
echo Html::dropDownList('list', 'null', $items);
?>
<div class="form-group">
<?=
Html::submitButton(
'Удалить отмеченные',[
'data' => ['confirm' => 'Вы действительно хотите перенести отмеченные товары в выбранную категорию?'],
'name' => 'deleteProduct',
'value' => 'delProduct', // добавить value
'class' => 'btn btn-danger'
])
?>
</div>
<?php ActiveForm::end(); ?>
And this in controller
if (Yii::$app->request->post('deleteProduct'))
{
$lk_number = $_POST['list'];
print_r($lk_number);exit();
}
But when click on button there is no catch in controller. What I do wrong?

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;
}
}

Yii2 different form fields on create and on update scenario

In my Model I have created different scenarios. I have one form which is rendered bu both create and update method. The form fields are as follows
Form.php
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model, $options = ['header'=>'', 'class'=>'pull-left errorDiv']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class'=>'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(),'item_name' ,'item_name');?>
<?= $form->field($mode, 'item_name')->dropDownList($items,[]);?>
<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(); ?>
On using update scenario I want only my email, firstname and last name to be rendered from the form.
const SCENARIO_REGISTER = 'signup';
const SCENARIO_CREATE = 'create';
const SCENARIO_UPDATE = 'update';
public function scenarios()
{
return [
self::SCENARIO_REGISTER => ['user_email', 'user_password_hash', 'user_fname', 'user_lname', 'agree','!user_password_hash_repeat','required'],
self::SCENARIO_CREATE => ['user_email', 'user_password_hash', 'user_fname', 'user_lname','!user_password_hash_repeat','required'],
self::SCENARIO_UPDATE => ['user_email', 'user_fname', 'user_lname', 'required'],
];
}
public static function tableName()
{
return 'sim_user';
}
And in my controller update method I am using scenario as below code.
public function actionUpdate($id)
{
$model = $this->findModel($id);
$model->scenario = SimUser::SCENARIO_UPDATE;
// var_dump($model->scenario); exit();
$mode = \app\modules\auth\models\SimAuthAssignment::find()->where(['user_id' => $id])->one();
if ($model->load(Yii::$app->request->post())&& $mode->load(Yii::$app->request->post())) {
$model->save();
return $this->redirect(['view', 'id' => $model->user_id]);
} else {
return $this->renderAjax('update', [
'model' => $model,
'mode' => $mode,
]);
}
}
I want to get only the email, firstname and lastname form fields to be rendered in the form when I edit. I want to ignore the others fields in the form when I edit. What am I missing here? Thanks!!
You are using an activeForm with all the inputField .. so all the fields are submit .. if you want only email, firstname and lastname
you should use another view with onnly these fields
<?php $form = ActiveForm::begin(); ?>
<?= $form->errorSummary($model, $options = ['header'=>'', 'class'=>'pull-left errorDiv']); ?>
<?= $form->field($model, 'user_fname')->textInput(['class'=>'form-control']);?>
<?= $form->field($model, 'user_lname')->textInput(['class'=>'form-control']); ?>
<?= $form->field($model,'user_email')->textInput(['class'=>'form-control']); ?>
<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(); ?>
The scenario then check only the fields you have ruled and the submit return only the data you need
You can use the $model->isNewRecord functionality
if(!$model->isNewRecord) {
echo $form->field('Your-field')->textInput(['class' => 'form-control');
}
If I got you right you want to hide some input elements depends on your form scenario.
So, this can be easily achieved using the following code:
<?php if ($model->isUpdating()) { ?>
<?= $form->field($model, 'user_fname')->textInput(['class' => 'form-control']); ?>
<?= $form->field($model, 'user_lname')->textInput(['class' => 'form-control']); ?>
<?= $form->field($model, 'user_email')->textInput(['class' => 'form-control']); ?>
<?php } ?>
<?php if ($model->isRegistration()) { ?>
<?= $form->field($model, 'user_password_hash')->passwordInput([]); ?>
<?= $form->field($model, 'user_password_hash_repeat')->passwordInput(['class' => 'form-control']); ?>
<?php $items = ArrayHelper::map(SimAuthAssignment::find()->all(), 'item_name', 'item_name'); ?>
<?= $form->field($mode, 'item_name')->dropDownList($items, []); ?>
<?php } ?>
According to this, add the following code to the form model:
public function isUpdating() : bool {
return $this->scenario === self::SCENARIO_REGISTER;
}
public function isRegistration() : bool {
return $this->scenario === self::SCENARIO_UPDATE;
}

Yii2 insert multiple records to other table

I want to make a checklist for user to check multiple option. And then when it save, value from checklist go to the "services" tables, the other details go to "post" table.
How can I insert multiples record to other tables from just one form. I'm stuck here and I really need helps.
My create function:
public function actionCreate()
{
$model = new Posts();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['category/index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
My form:
<div class="col-lg-5">
<?php $form = ActiveForm::begin(['id' => 'station-form', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'name') ?>
<?= $form->field($model, 'address') ?>
<?= $form->field($model, 'phone') ?>
<?= $form->field($model, 'price') ?>
<?= $form->field($model, 'square') ?>
<?= $form->field($model, 'content')->textarea() ?>
<?= $form->field($model, 'services_id[]')->checkboxList($items2) ?>
If You have two models for
services and post
Given Below that i had done
My _form.php
It Contain Two Models
1.$model for Login details.
2.$condact for contact details.
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'username')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'password')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($condact, 'name') ->textInput(['maxlength' => true]) ?>
<?= $form->field($condact, 'address')->textArea(['rows' => '6']) ?>
My controller
LogindetailsController.php
public function actionCreate()
{
$model = new Logindetails();
$condact= new Condactdetails();
if ( $model->load(Yii::$app->request->post()) && $condact->load(Yii::$app->request->post()) ) {
$model->save();
$condact->logid = $model->logid;
if($condact->save()){
return $this->redirect(['view', 'id' => $model->logid]);
}
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
In this way I have Insert into multiple tables.
I think This answer will help u to.