Yii2 insert multiple records to other table - yii2

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.

Related

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 update a record based on form in a view file

I tried to update one field of record based on value in a form. The form are placed within a modal in a view file.
view
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
But I have no idea how to pass those value to my controller so it can update whatever the user have input and submitted.
Controller
public function actionPay($id)
{
$model = Purchase::findOne($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->pcstatus = 'Paid';
$model->pcpaydate = date('Y-m-d H:i:s');
$model->save();
return $this->redirect(['view', 'id' => $model->pcid]);
}
}
I'm new to Yii framework. Any help is much appreciated.
EDIT
The only thing I want to do is to update only this field (current record/view) into database instead of update the whole field.
You must set action in your form with id, it will work
Modal::begin([
'header' => '<h3>Update Payment Reference</h3>',
'toggleButton' => ['label' => 'Pay','class' => 'btn btn-success'],
]); ?>
<?php $form = ActiveForm::begin([
'action' => ['controller/pay','id'=>$id],
]); ?>
<?= $form->field($model, 'pcpayreference')->textInput(['maxlength' => true]) ?>
<?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
<?php Modal::end();
I think this is the problem regarding csrf validation, just make sure in your config about enableCsrfValidation :
just put this function in your controller
public function beforeAction($action) {
$this->enableCsrfValidation = false;
return parent::beforeAction($action);
}
Let me know please.

yii2: js calulation in server side

This is a page for calculate the product order.
My mentor told me that:
"The code put the code calculation logic inside JavaScript which means, user can simply inject and modified the content and get discount to make it safe, may either do a recalculation on submit at server side before display, or make the js function to call API, and return the result instead of put calculation logic inside JS"
But I really can't get it, how can I make it in server side?
views:
<?php $form = ActiveForm::begin([
'action'=>['summary'],
'id'=>'order-form',
]); ?>
<?= Html::dropDownList('country', null,['malaysia'=>'Malaysia','singapore'=>'Singapore', 'brunei'=>'Brunei'],['id'=>'country']) ?>
<?= Html::textInput('code','',['class'=>'form-control','placeholder'=>'promotion code','id'=>'code', 'style'=>'text-transform:uppercase'])?>
<?= Html::button('Apply', ['class' => 'btn btn-primary', 'id'=>'apply']) ?>
<?= Html::hiddenInput('id', $model->id) ?>
<?= Html::hiddenInput('discount', '', ['id'=>'discount']) ?>
<?= Html::hiddenInput('ship','',['id'=>'ship']) ?>
<?= Html::hiddenInput('qty', $qty, ['id'=>'qty']) ?>
<?= Html::hiddenInput('subtotal', $subtotal, ['id'=>'subtotal']) ?>
<?= Html::submitButton('Checkout', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
js:
$(document).ready(function() {
var qty=$('#qty').val();
var subtotal=$('#subtotal').val();
$('#discount').val(0);
$("#apply").click(function() {
var code=$('#code').val().toUpperCase();
var off5=(subtotal*0.05).toFixed(2);
var off15=15;
if(code=='OFF5PC'){
if (qty>=2)
$('#discount').val(off5);
else{
$('#discount').val(0);
alert('At least 2 quantities');
}
}
else if(code=='GIVEME15'){
if(subtotal>=100)
$('#discount').val(off15);
else{
$('#discount').val(0);
alert('Minumum puchase of RM100');
}
}
else{
$('#discount').val(0);
alert('Invalid promotion code');
}
if ($('#discount').val()=='0'){
$('#code').val('');
}
});
if(qty>=2||subtotal>=150){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(10);
$('#shipping').html('10');
}
$("#country").change(function() {
var country=$('#country').val();
if(country=='malaysia'){
if(qty>=2||subtotal>=150){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(10);
$('#shipping').html('10');
}
}
else if(country=='singapore'){
if(subtotal>=300){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(20);
$('#shipping').html('20');
}
}
else if(country=='brunei') {
if(subtotal>=300){
$('#ship').val(0);
$('#shipping').html('0');
}
else{
$('#ship').val(25);
$('#shipping').html('25');
}
}
});
});
controllers:
public function actionSummary()
{
$id=Yii::$app->request->post('id');
$qty=Yii::$app->request->post('qty');
$discount=Yii::$app->request->post('discount');
$shipping=Yii::$app->request->post('ship');
$subtotal=Yii::$app->request->post('subtotal');
$area=Yii::$app->request->post('country');
$code=Yii::$app->request->post('code');
$summary=Products::findOne($id);
return $this->render('summary', [
'model' => $summary,
'quantity'=>$qty,
'discount'=>$discount,
'shipping'=>$shipping,
'subtotal'=>$subtotal,
'area'=>$area,
'code'=>$code,
]);
}
use browser tools inspect to determine your id of each fields. Usually the default id in Yii2 begins with view_name combine with "-" and field name.
For validating the form onsubmit, you can enable ajaxvalidation in your form like below.
View:
<?php $form = ActiveForm::begin([
'action'=>['summary'],
'enableAjaxValidation' => true,
'id'=>'order-form',
]); ?>
<?= $form->field($model, 'country')->dropDownList(['malaysia'=>'Malaysia','singapore'=>'Singapore', 'brunei'=>'Brunei']) ?>
<?= $form->field($model, 'code', ['options' => ['class' => 'form-control', 'id'=>'code']])->textInput(['placeholder'=>'promotion code'])?>
<?= Html::button('Apply', ['class' => 'btn btn-primary', 'id'=>'apply']) ?>
<?= Html::hiddenInput('id', $model->id) ?>
<?= Html::hiddenInput('discount', '', ['id'=>'discount']) ?>
<?= Html::hiddenInput('ship','',['id'=>'ship']) ?>
<?= Html::hiddenInput('qty', $qty, ['id'=>'qty']) ?>
<?= Html::hiddenInput('subtotal', $subtotal, ['id'=>'subtotal']) ?>
<?= Html::submitButton('Checkout', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end(); ?>
In your controller file, please add the ajax validation code in your controller before inserting into database. Below is the example ajax validation code for validating from server side.
Controller:
public function actionYourActionName(){
$model = new YourModelClass();
if ($model->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if($model->save())){
//after successful save if you want to do any thing those codes will goes here.
}
}
return $this->render('your-view-file-name', ['model' => $model]);
}
Model:
<?php
namespace app\models;
use yii;
use yii\db\ActiveRecord;
class YourModelClass extends ActiveRecord
{
...
public function rules(){
return [
[['id', 'discount', 'ship', 'qty', 'subtotal'], 'safe'],
[['country', 'code'], 'required']
];
...
}
?>

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: How to save form data in two tables from one form?

public function actionCreate()
{
$model = new CreateClient1();
$employee = new Employee();
if ($model->load(Yii::$app->request->post()) && $employee->load(Yii::$app->request->post()))
{
$model->save();
/*add same field in employee table*/
$employee->client_code = $model->client_code;
$employee->company_name = $model->company_name;
$employee->emp_first_name = $model->emp_first_name;
$employee->emp_last_name = $model->emp_last_name;
$employee->emp_email = $model->emp_email;
$employee->emp_mobile = $model->emp_mobile;
$employee->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
'employee' => $employee,
]);
}
}
My form looks like this do i need to add something in it?
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
/* #var $this yii\web\View */
/* #var $model backend\models\CreateClient1 */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="create-client1-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?= Html::activeHiddenInput($model, 'client_code', ['value' => rand(1,100000000000000)]) ?>
<?= $form->field($model, 'company_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_mobile')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_first_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'emp_last_name')->textInput(['maxlength' => true]) ?>
</div>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
Trying to insert same data in two tables.
Table CreateClient1 and Employee has to be same data, how do I insert in to Employee table in Yii2.
Any thing needs to add in form? my form form is not submitting
Try this:
public function actionCreate()
{
$model = new CreateClient1();
$employee = new Employee();
if ($model->load(Yii::$app->request->post()))
{
$model->save();
/*add same field in employee table*/
$employee->attributes = $model->attributes;
$employee->save();
return $this->redirect(['view', 'id' => $model->id]);
} else
{
return $this->render('create', [
'model' => $model,
'employee' => $employee,
]);
}
}