Tech Programming Ideas is one of the best places on the programming for programmers. Learn coding with Tech Programming Ideas tutorials. We are covered android programming, php, yii2 framework, javascript, mysql, vb.net etc.
When you submit form by pressing enter (without click any submit button), submit_1 will be default value.
or other methord
if(Yii::$app->request->post()){if(Yii::$app->request->post('submit')== 'submit_1'){//Code for submit button 1}if(Yii::$app->request->post('submit')== 'submit_2'){//Code for submit button 2}}
or other methord
publicfunction actionYourControllerName(){if(isset($_POST['submit')&& $_POST['submit']=='next'){// your code}elseif(isset($_POST['submit'])&& $_POST['submit']=='previous'){// your code}}
to the require section of your composer.json file.
Videos
Project Starting
Step 1
First create table of po and po_item and relationship Po table Structure
* Set id as primary and auto increment
Po_item table Structure
* Set id as primary and auto increment
* po_id set INDEX
Now the next thing we have to create a relationship po_item.
Step 2
Using gii to create model, controller and view (CRUD Operations)
Step 3
Create operations
Edit view file _form.php under views/po Edit controller file PoController.php under controllers Add new file Model.php in models Edit model PoItem.php, po_id property removed required
$(".dynamicform_wrapper").on("beforeInsert", function(e, item) {
console.log("beforeInsert");
});
$(".dynamicform_wrapper").on("afterInsert", function(e, item) {
console.log("afterInsert");
});
$(".dynamicform_wrapper").on("beforeDelete", function(e, item) {
if (!confirm("Are you sure you want to delete this item?")) {
returnfalse;
}
returntrue;
});
$(".dynamicform_wrapper").on("afterDelete", function(e) {
console.log("Deleted item!");
});
$(".dynamicform_wrapper").on("limitReached", function(e, item) {
alert("Limit reached");
});
The Controller (sample code)
<?php
namespace backend\modules\dynamicform\controllers;
use Yii;
use backend\modules\dynamicform\models\Po;
use backend\modules\dynamicform\models\PoSearch;
use backend\modules\dynamicform\models\PoItem;
use backend\modules\dynamicform\models\Model;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
/**
* PoController implements the CRUD actions for Po model.
*/
class PoController extends Controller
{
/**
* @inheritdoc
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
];
}
/**
* Lists all Po models.
* @return mixed
*/
public function actionIndex()
{
$searchModel = new PoSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
/**
* Displays a single Po model.
* @param integer $id
* @return mixed
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Po model.
* If creation is successful, the browser will be redirected to the 'view' page.
* @return mixed
*/
public function actionCreate()
{
$model = new Po();
$modelsPoItem = [new PoItem];
if ($model->load(Yii::$app->request->post())) {
$modelsPoItem = Model::createMultiple(PoItem::classname());
Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsPoItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsPoItem as $modelPoItem)
{
$modelPoItem->po_id = $model->id;
if (! ($flag = $modelPoItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('create', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new PoItem] : $modelsPoItem
]);
}
}
/**
* Updates an existing model.
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsPoItem = $model->poItems;
if ($model->load(Yii::$app->request->post())) {
$oldIDs = ArrayHelper::map($modelsPoItem, 'id', 'id');
$modelsPoItem = Model::createMultiple(PoItem::classname(), $modelsPoItem);
Model::loadMultiple($modelsPoItem, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsPoItem, 'id', 'id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsPoItem) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
PoItem::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsPoItem as $modelPoItem) {
$modelPoItem->po_id = $model->id;
if (! ($flag = $modelPoItem->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('update', [
'model' => $model,
'modelsPoItem' => (empty($modelsPoItem)) ? [new Address] : $modelsPoItem
]);
}
}
/**
* Deletes an existing Po model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* @param integer $id
* @return mixed
*/
public function actionDelete($id)
{
PoItem::deleteAll(['po_id'=>$id]);
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
/**
* Finds the Po model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* @param integer $id
* @return Po the loaded model
* @throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Po::findOne($id)) !== null) {
return $model;
} else {
throw new NotFoundHttpException('The requested page does not exist.');
}
}
}
Model Class Model.php
<?php
//add your name space
namespace backend\modules\dynamicform\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;
}
}
'components'=>[...'formatter'=>['class'=>'yii\i18n\Formatter','dateFormat'=>'php:j M Y','datetimeFormat'=>'php:j M Y H:i','timeFormat'=>'php:H:i','timeZone'=>'Europe/Berlin',],
Sometimes we want to collect user input in a batch mode. That is, the user can enter the information for multiple model instances and submit them all at once. We call this tabular input because the input fields are often presented in an HTML table.
To work with tabular input, we first need to create or populate an array of model instances, depending on whether we are inserting or updating the data. We then retrieve the user input data from the $_POST variable and assign it to each model. A slight difference from single model input is that we retrieve the input data using $_POST['ModelClass'][$i] instead of$_POST['ModelClass'].
In contrast to the single model forms explained before, we are working with an array of models now. This array is passed to the view to display the input fields for each model in a table like style and we will use helper methods of yii\base\Model that allow loading and validating multiple models at once:
This example for validate and save tabular data. Help to avoid insert many times the same table with ActiveForm.
Modify your controller code to use multiple models
<?php
namespace backend\modules\tools\controllers;
use Yii;
use backend\modules\tools\models\Products;
use backend\modules\tools\models\ProductsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter; use yii\base\Model;
/**
* ProductsController implements the CRUD actions for Products model.
*/
class ProductsController extends Controller
{
.................
................
public function actionCreate() { //Find out how many products have been submitted by the form //$count = count(Yii::$app->request->post('Product', [])); $count=4; //Send at least one model to the form $prts = [new Products()]; //Create an array of the products submitted for($i = 1; $i < $count; $i++) { $prts[] = new Products(); } //Load and validate the multiple models if (Model::loadMultiple($prts, Yii::$app->request->post()) && Model::validateMultiple($prts)) { foreach ($prts as $product) { //Try to save the models. Validation is not needed as it's already been done. $product->save(false); } return $this->redirect('view'); } return $this->render('create', ['prts' => $prts]); }
..........
...........
}
The view file for the form needs to be altered like this, to use the multiple models;