Yii2 log in form works only when ajaxvalidation is false - yii2

I have a log in form which works only when i turn of my ajaxValidation. If i enable itenableAjaxValidation = true` it dies. What is the problem? Is it something with the model rules? On the previous projects i used the same form and all was fine. Can't realize. Can you guys give an advice and quick explanation. Thank you in advance!
<div class="row">
<div class="col-xs-12">
<h3 class="contact-page-title"><?= Yii::t('app', 'app.Login') ?></h3>
<?php if (Yii::$app->user->isGuest): ?>
<?php $form = ActiveForm::begin([
'id' => 'login-widget-form',
'action' => Url::to(['/user/security/login']),
/*'enableAjaxValidation' => true,*/
'enableClientValidation' => false,
'validateOnBlur' => false,
'validateOnType' => false,
'validateOnChange' => false,
]) ?>
<?= $form->field($model, 'login')->textInput() ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'rememberMe')->checkbox() ?>
<input type="hidden" name="checkoutLogin" value="1">
<?= Html::submitButton(Yii::t('user', Yii::t('app','app.Login')) , ['class' => 'btn-1 shadow-0 full-width']) ?>
<?php ActiveForm::end(); ?>
<?php else: ?>
<?= Html::a(Yii::t('user', 'Logout'), ['/user/security/logout'], [
'class' => 'btn btn-danger btn-block',
'data-method' => 'post'
]) ?>
<?php endif ?>
</div>
</div>
And these are the rules:
public function rules()
{
$rules = [
'loginTrim' => ['login', 'trim'],
'requiredFields' => [['login'], 'required'],
'confirmationValidate' => [
'login',
function ($attribute) {
if ($this->user !== null) {
$confirmationRequired = $this->module->enableConfirmation
&& !$this->module->enableUnconfirmedLogin;
if ($confirmationRequired && !$this->user->getIsConfirmed()) {
$this->addError($attribute, Yii::t('user', 'You need to confirm your email address'));
}
if ($this->user->getIsBlocked()) {
$this->addError($attribute, Yii::t('user', 'Your account has been blocked'));
}
}
}
],
'rememberMe' => ['rememberMe', 'boolean'],
];
if (!$this->module->debug) {
$rules = array_merge($rules, [
'requiredFields' => [['login', 'password'], 'required'],
'passwordValidate' => [
'password',
function ($attribute) {
if ($this->user === null || !Password::validate($this->password, $this->user->password_hash)) {
$this->addError($attribute, Yii::t('user', 'Invalid login or password'));
}
}
]
]);
}
return $rules;
}
EDIT Action:
public function actionLogin() {
if (!Yii::$app->user->isGuest) {
$this->goHome();
}
$register = new RegistrationForm();
if(Yii::$app->request->isAjax){
return 1;
}
/** #var LoginForm $model */
$model = Yii::createObject(LoginForm::className());
$event = $this->getFormEvent($model);
$this->performAjaxValidation($model);
$this->trigger(self::EVENT_BEFORE_LOGIN, $event);
if ($model->load(Yii::$app->getRequest()->post()) && $model->login()) {
$this->trigger(self::EVENT_AFTER_LOGIN, $event);
//return $this->goBack();
if (Yii::$app->request->baseUrl == "" and !isset($_POST["checkoutLogin"])) {
$session = Yii::$app->session;
return $this->redirect('/');
} elseif(isset($_POST["checkoutLogin"]) and $_POST["checkoutLogin"] == 1) {
$lang = \frontend\models\Lang::getCurrent();
$checkout = Page::findOne(91);
if($checkout){
return $this->redirect('/'.$lang->url.'/'.$checkout->url);
}else{
return $this->goBack();
}
} else {
return $this->goBack();
}
}
return $this->render('login', [
'model' => $model,
'module' => $this->module,
'register' => $register
]);
}

Try with the code of performAjaxValidation() moved to the action:
// instead of $this->performAjaxValidation($model);
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}

Related

Can't delete selected image when update the form by using Yii kartik fileinput

I refer to this link https://github.com/jaradsee/faktharm/blob/master/controllers/PhotoLibraryController.php
to upload multiple images but when I try to delete the selected image in update form it showing me these error
(image1)
(image2)
For image 2, why the url link always give products%252Fdeletefile-ajax (give number 25)
Below is my code, please help me to check what's goes wrong, thank you!
Uploads.php
class Uploads extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
public static function tableName()
{
return 'uploads';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['file_name'], 'required'],
[['upload_id'], 'integer'],
[['create_date'], 'safe'],
[['ref'], 'string', 'max' => 100],
[['file_name', 'real_filename'], 'string', 'max' => 150],
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'upload_id' => 'Upload ID',
'ref' => 'Ref',
'file_name' => 'File Name',
'real_filename' => 'Real Filename',
'create_date' => 'Create Date',
];
}
}
Products.php
class Products extends \yii\db\ActiveRecord
{
/**
* {#inheritdoc}
*/
//public $file;
const UPLOAD_FOLDER='products';
public static function tableName()
{
return 'products';
}
/**
* {#inheritdoc}
*/
public function rules()
{
return [
[['productName', 'productDescription', 'productPrice', 'categoryId', 'brandId', 'productStatus'], 'required'],
[['productDescription', 'productStatus'], 'string'],
[['productPrice'], 'number'],
[['categoryId', 'brandId'], 'integer'],
[['productName','ref'], 'string', 'max' => 100],
[['brandId'], 'exist', 'skipOnError' => true, 'targetClass' => Brands::className(), 'targetAttribute' => ['brandId' => 'brandId']],
[['categoryId'], 'exist', 'skipOnError' => true, 'targetClass' => Categorys::className(), 'targetAttribute' => ['categoryId' => 'categoryId']],
[['ref'],'unique']
// ['productImage', 'file','maxFiles'=>5],
//[['file'],'productImage']
];
}
/**
* {#inheritdoc}
*/
public function attributeLabels()
{
return [
'productId' => 'Product ID',
'productName' => 'Product Name',
'productDescription' => 'Product Description',
'productPrice' => 'Product Price',
'ref' => 'Product Image',
'categoryId' => 'Category',
'brandId' => 'Brand',
'productStatus' => 'Product Status',
];
}
/**
* Gets query for [[Brand]].
*
* #return \yii\db\ActiveQuery
*/
public function getBrand()
{
return $this->hasOne(Brands::className(), ['brandId' => 'brandId']);
}
/**
* Gets query for [[Category]].
*
* #return \yii\db\ActiveQuery
*/
public function getCategory()
{
return $this->hasOne(Categorys::className(), ['categoryId' => 'categoryId']);
}
public function getImages()
{
return $this->hasMany(Images::className(), ['productId' => 'productId']);
}
public static function getUploadPath(){
return Yii::getAlias('#webroot').'/'.self::UPLOAD_FOLDER.'/';
}
public static function getUploadUrl(){
return Url::base(true).'/'.self::UPLOAD_FOLDER.'/';
}
public function getThumbnails($ref,$event_name){
$uploadFiles = Uploads::find()->where(['ref'=>$ref])->all();
$preview = [];
foreach ($uploadFiles as $file) {
$preview[] = [
'url'=>self::getUploadUrl(true).$ref.'/'.$file->real_filename,
'src'=>self::getUploadUrl(true).$ref.'/thumbnail/'.$file->real_filename,
'options' => ['title' => $event_name]
];
}
return $preview;
}
}
ProductsController.php
namespace backend\controllers;
use Yii;
use backend\models\Products;
use backend\models\Uploads;
use backend\models\ProductsSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\helpers\Json;
use yii\widgets\ActiveForm;
use yii\web\UploadedFile;
use yii\helpers\Url;
use yii\helpers\html;
use yii\helpers\BaseFileHelper;
use yii\helpers\ArrayHelper;
/**
* ProductsController implements the CRUD actions for Products model.
*/
class ProductsController extends Controller
{
/**
* {#inheritdoc}
*/
public function behaviors()
{
return [
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['POST'],
],
],
// 'access' => [
// 'class' => AccessControl::className(),
// 'rules' => [
// [
// 'actions' => ['view','update','_form','index','_search','create','uploadAjax','createDir'],
// 'allow' => true,
// 'roles' => ['admin'],
// ],
// ],
// ],
];
}
/**
* Lists all Products models.
* #return mixed
*/
public function actionIndex($pageSize = 10)
{
$searchModel = new ProductsSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams, $pageSize);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
'pageSize' => $pageSize,
]);
}
/**
* Displays a single Products model.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
/**
* Creates a new Products model.
* If creation is successful, the browser will be redirected to the 'view' page.
* #return mixed
*/
/*public function actionCreate()
{
$model = new Products();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$model->imageFiles = UploadedFile::getInstances($model, 'productImage');
return $this->redirect(['view', 'id' => $model->productId]);
}
return $this->render('create', [
'model' => $model,
]);
}*/
public function actionCreate()
{
$model = new Products();
if ($model->load(Yii::$app->request->post())) {
$this->Uploads(false);
if($model->save()){
return $this->redirect(['view', 'id' => $model->productId]);
}
}
else{
$model->ref = substr(Yii::$app->getSecurity()->generateRandomString(),10);
}
return $this->render('create', [
'model' => $model,
]);
}
/**
* Updates an existing Products model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
list($initialPreview,$initialPreviewConfig) = $this->getInitialPreview($model->ref);
if ($model->load(Yii::$app->request->post())) {
$this->Uploads(false);
if($model->save()){
return $this->redirect(['view', 'id' => $model->productId]);
}
}
return $this->render('update', [
'model' => $model,
'initialPreview'=>$initialPreview,
'initialPreviewConfig'=>$initialPreviewConfig
]);
}
/**
* Deletes an existing Products model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
* #throws NotFoundHttpException if the model cannot be found
*/
public function actionDelete($id)
{
//$model = new Products();
//$this->findModel($id)->delete();
$model->$this->findModel($id);
$this->removeUploadDir($model->ref);
Uploads::deleteAll(['ref'=>$model->ref]);
$model->delete();
return $this->redirect(['index']);
}
/**
* Finds the Products model based on its primary key value.
* If the model is not found, a 404 HTTP exception will be thrown.
* #param integer $id
* #return Products the loaded model
* #throws NotFoundHttpException if the model cannot be found
*/
protected function findModel($id)
{
if (($model = Products::findOne($id)) !== null) {
return $model;
}
throw new NotFoundHttpException('The requested page does not exist.');
}
/*|*********************************************************************************|
|================================ Upload Ajax ====================================|
|*********************************************************************************|*/
public function actionUploadAjax(){
$this->Uploads(true);
}
private function CreateDir($folderName){
if($folderName != NULL){
$basePath = Products::getUploadPath();
if(BaseFileHelper::createDirectory($basePath.$folderName,0777)){
BaseFileHelper::createDirectory($basePath.$folderName.'/thumbnail',0777);
}
}
return;
}
private function removeUploadDir($dir){
BaseFileHelper::removeDirectory(Products::getUploadPath().$dir);
}
private function Uploads($isAjax=false) {
if (Yii::$app->request->isPost) {
$images = UploadedFile::getInstancesByName('upload_ajax');
if ($images) {
if($isAjax===true){
$ref =Yii::$app->request->post('ref');
}else{
$Products = Yii::$app->request->post('Products');
$ref = $Products['ref'];
}
$this->CreateDir($ref);
foreach ($images as $file){
$fileName = $file->baseName . '.' . $file->extension;
$realFileName = md5($file->baseName.time()) . '.' . $file->extension;
$savePath = Products::UPLOAD_FOLDER.'/'.$ref.'/'. $realFileName;
if($file->saveAs($savePath)){
if($this->isImage(Url::base(true).'/'.$savePath)){
$this->createThumbnail($ref,$realFileName);
}
$model = new Uploads;
$model->ref = $ref;
$model->file_name = $fileName;
$model->real_filename = $realFileName;
$model->save();
if($isAjax===true){
echo json_encode(['success' => 'true']);
}
}else{
if($isAjax===true){
echo json_encode(['success'=>'false','eror'=>$file->error]);
}
}
}
}
}
}
private function getInitialPreview($ref) {
$datas = Uploads::find()->where(['ref'=>$ref])->all();
$initialPreview = [];
$initialPreviewConfig = [];
foreach ($datas as $key => $value) {
array_push($initialPreview, $this->getTemplatePreview($value));
array_push($initialPreviewConfig, [
'caption'=> $value->file_name,
'width' => '120px',
'url' => Url::to(['/products/deletefile-ajax']),
'key' => $value->upload_id
]);
}
return [$initialPreview,$initialPreviewConfig];
}
public function isImage($filePath){
return #is_array(getimagesize($filePath)) ? true : false;
}
private function getTemplatePreview(Uploads $model){
$filePath = Products::getUploadUrl().$model->ref.'/thumbnail/'.$model->real_filename;
$isImage = $this->isImage($filePath);
if($isImage){
$file = Html::img($filePath,['class'=>'file-preview-image', 'alt'=>$model->file_name, 'title'=>$model->file_name]);
}else{
$file = "<div class='file-preview-other'> " .
"<h2><i class='glyphicon glyphicon-file'></i></h2>" .
"</div>";
}
return $file;
}
private function createThumbnail($folderName,$fileName,$width=250){
$uploadPath = Products::getUploadPath().'/'.$folderName.'/';
$file = $uploadPath.$fileName;
$image = Yii::$app->image->load($file);
$image->resize($width);
$image->save($uploadPath.'thumbnail/'.$fileName);
return;
}
public function actionDeletefileAjax(){
$model = Uploads::findOne(Yii::$app->request->post('key'));
if($model!==NULL){
$filename = Products::getUploadPath().$model->ref.'/'.$model->real_filename;
$thumbnail = Products::getUploadPath().$model->ref.'/thumbnail/'.$model->real_filename;
if($model->delete()){
#unlink($filename);
#unlink($thumbnail);
echo json_encode(['success'=>true]);
}else{
echo json_encode(['success'=>false]);
}
}else{
echo json_encode(['success'=>false]);
}
}
}
_form.php
<?php
//use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use backend\models\Brands;
use backend\models\Categorys;
use yii\helpers\Url;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Products */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="photo-library-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php $form->errorSummary($model) ?>
<?= $form->field($model, 'ref')->hiddenInput(['maxlength' => 100])->label(false); ?>
<?= $form->field($model, 'productName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'productDescription')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'productPrice')->textInput() ?>
<?=
$form->field($model, 'brandId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Brands::find()->where(['brandStatus'=>'active'])->all(),'brandId','brandName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a brand ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?=
$form->field($model, 'categoryId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Categorys::find()->where(['categoryStatus'=>'active'])->all(),'categoryId','categoryName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a category ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'productStatus')->dropDownList([ 'active' => 'Active', 'inactive' => 'Inactive', ], ['prompt' => 'Status']) ?>
<div class="form-group field-upload_files">
<label class="control-label" for="upload_files[]"> Product Images </label>
<div>
<?=
FileInput::widget([
'name' => 'upload_ajax[]',
//'attribute'=>'productImage[]',
//'name'=>'productImage[]',
'options' => [
'multiple'=>true,
'accept' => 'image/*',
//'id'=>'imageId',
],
'pluginOptions' => [
'initialPreview'=> $initialPreview,
'initialPreviewConfig'=> $initialPreviewConfig,
'deleteUrl'=>Url::to(['/products/deletefile-ajax']),
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'uploadAsync' => true,
'uploadUrl'=>Url::to(['/products/upload-ajax']),
'maxFileCount' => 5,
'allowedFileExtensions' => ['jpg', 'png','jpeg'],
'previewFileType' => ['jpg', 'png','jpeg'],
'overwriteInitial'=>false,
'uploadExtraData' => [
'ref'=>$model->ref
],
'msgUploadBegin' => Yii::t('app', 'Please wait, system is uploading the files'),
'validateInitailCount'=>true,
'layoutTemplates'=>[
'actionZoom'=>'<button type="button" class="kv-file-zoom">{zoomIcon}</button>',
'actionUpload'=>'',
//'actionDelete'=>'<a>jj</a>',
//'footer' => '<div class="file-thumbnail-footer"><div class="file-caption-name" style="width:{width}">{caption}{size}</div>
//{progress}{actions}',
//'footer' => '<div class="file-thumbnail-footer"> <div class="file-caption-caption" title="{caption}"</div>'
//'actionDelete'=>'<button type="button" class="kv-file-remove"> {dataKey}{deleteUrl} {removeIcon}</button>',
],
],
'pluginEvents' => [
'filebatchselected' => 'function(event, files) {
$(this).fileinput("/products/upload-ajax");
}',
],
]);
?>
<br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord? 'Save': 'Update', ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Cancel'), ['index', 'id' => $model->productId], ['class'=>'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
I found the solution my bad
need to change all the Url::to() in controller and _form
to this format solution
The detail answer as below
_form.php
<?php
//use kartik\file\FileInput;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use backend\models\Brands;
use backend\models\Categorys;
use yii\helpers\Url;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $model backend\models\Products */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="photo-library-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data']]); ?>
<?php $form->errorSummary($model) ?>
<?= $form->field($model, 'ref')->hiddenInput(['maxlength' => 100])->label(false); ?>
<?= $form->field($model, 'productName')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'productDescription')->textarea(['rows' => 6]) ?>
<?= $form->field($model, 'productPrice')->textInput() ?>
<?=
$form->field($model, 'brandId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Brands::find()->where(['brandStatus'=>'active'])->all(),'brandId','brandName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a brand ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?=
$form->field($model, 'categoryId')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Categorys::find()->where(['categoryStatus'=>'active'])->all(),'categoryId','categoryName'),
'language' => 'en',
'options' => ['placeholder' => 'Select a category ...'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
<?= $form->field($model, 'productStatus')->dropDownList([ 'active' => 'Active', 'inactive' => 'Inactive', ], ['prompt' => 'Status']) ?>
<label>Product Images</label>
<?=
FileInput::widget([
'name' => 'upload_ajax[]',
//'attribute'=>'productImage[]',
//'name'=>'productImage[]',
'options' => [
'multiple'=>true,
'accept' => 'image/*',
//'id'=>'imageId',
],
'pluginOptions' => [
'initialPreview'=> $initialPreview,
'initialPreviewConfig'=> $initialPreviewConfig,
'showPreview' => true,
'showCaption' => false,
'showRemove' => false,
'showUpload' => false,
'uploadAsync' => false,
'uploadUrl'=>Url::to('index.php?r=products/upload-ajax'),
'deleteUrl'=>Url::to('index.php?r=products/deletefile-ajax'),
'maxFileCount' => 5,
'allowedFileExtensions' => ['jpg', 'png','jpeg'],
'previewFileType' => ['jpg', 'png','jpeg'],
'overwriteInitial'=>false,
'enableResumableUpload'=>true,
'uploadExtraData' => [
'ref'=>$model->ref
],
'validateInitialCount'=>true,
'initialPreviewShowDelete' => true,
'layoutTemplates'=>[
'actionZoom'=>'<button type="button" class="kv-file-zoom">{zoomIcon}</button>',
'actionUpload'=>'',
'actionDelete' => '<button type="button" class="kv-file-remove" title="{removeTitle}" {dataKey}{dataUrl}><i class="glyphicon glyphicon-trash"></i></button>'
],
],
'pluginEvents' => [
// 'filebatchselected' => 'function(files) {
// $(this).fileinput("index.php?r=products/upload-ajax");
// }',
'filepredelete'=>'function(jqXHR){
var abort = true;
if (confirm("Are you sure you want to delete this image?")) {
abort = false;
}
return abort;
}'
],
]);
?>
<br>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord? 'Save': 'Update', ['class' => 'btn btn-primary']) ?>
<?= Html::a(Yii::t('app', 'Cancel'), ['index', 'id' => $model->productId], ['class'=>'btn btn-danger']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
ProductsController
private function getInitialPreview($ref) {
$datas = Uploads::find()->where(['ref'=>$ref])->all();
$initialPreview = [];
$initialPreviewConfig = [];
foreach ($datas as $key => $value) {
array_push($initialPreview, $this->getTemplatePreview($value));
array_push($initialPreviewConfig, [
'caption'=> $value->file_name,
'width' => '120px',
'url' => Url::to('index.php?r=products/deletefile-ajax'),
'key' => $value->upload_id
]);
}
return [$initialPreview,$initialPreviewConfig];
}

Yii2 uploadfile image from model method beforeSave

i try to upload 4 or less images, the ajax validation do not return any error, but on submit i get the follow:
"errors": {
"imageFiles": [
"Please upload a file."
]
}
attr:
/**
* #var UploadedFile[]
*/
public $imageFiles;
Rules:
return [
[['imageFiles'], 'required', 'on' => self::REPORT_STEP1],
[['imageFiles'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 4],
];
BeforeSave:
public function beforeSave($insert)
{
$files_urls = [];
$this->imageFiles = UploadedFile::getInstances($this, 'imageFiles');
foreach ($this->imageFiles as $file) {
$path = Url::to(['/uploads/reports/'], true) . Yii::$app->security->generateRandomString() . '.' . $file->extension;
$file->saveAs($path);
$files_urls[] = $file->name;
}
$this->img_url = json_encode($files_urls);
return parent::beforeSave($insert); // TODO: Change the autogenerated stub
}
Form:
<?php $form = ActiveForm::begin([
'enableAjaxValidation' => true,
'options' => [
'enctype' => 'multipart/form-data'
]
]) ?>
<?= $form->field($model, 'imageFiles[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<div class="form-group">
<?= Html::submitButton('Siguiente', ['class' => 'btn btn-standard']) ?>
</div>
<?php ActiveForm::end() ?>

Yii2 Automatically Login after Registration

I'm creating a website using yii2 framework. I have a problem in registration. I have a modal in home and it contains the sign up form. Now when i trying to register, Yes it saved successful but it only stay in the modal. Now i want is after registering it will automatically login.
This is my sign up form_:
<div class="row">
<div class="col-lg-12">
<?php yii\widgets\Pjax::begin(['id' => 'sign-up']) ?>
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['data-pjax' => true]]); ?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($model, 'role')->dropDownList(['2' => 'User', '1' => 'Encoder', '3' => 'Admin']) ?>
<?= $form->field($model, 'username')->textInput(['placeholder' => 'Username....']) ?>
<?= $form->field($model, 'email')->textInput(['placeholder' => 'Email....']) ?>
<?= $form->field($model, 'password')->passwordInput(['placeholder' => 'Password.....']) ?>
</div>
<div class="col-sm-6">
<?= $form->field($model, 'confirmPassword')->passwordInput(['placeholder' => 'Confirm Password.....']) ?>
<?= $form->field($model, 'first_name')->textInput(['placeholder' => 'First Name....']) ?>
<?= $form->field($model, 'middle_name')->textInput(['placeholder' => 'Middle Name....']) ?>
<?= $form->field($model, 'last_name')->textInput(['placeholder' => 'Last Name....']) ?>
</div>
</div>
<center>
<?= $form->field($model, 'verifyCode')->widget(Captcha::className()) ?>
</center>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button', 'style' => 'width: 100%; padding: 10px;']) ?>
</div>
<?php ActiveForm::end(); ?>
<?php yii\widgets\Pjax::end() ?>
</div>
</div>
This is my model:
class SignupForm extends Model
{
public $role;
public $username;
public $email;
public $password;
public $first_name;
public $middle_name;
public $last_name;
public $confirmPassword;
public $verifyCode;
public function rules()
{
return [
['role', 'required'],
['username', 'trim'],
['username', 'required'],
['username', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This username has already been taken.'],
['username', 'string', 'min' => 2, 'max' => 20],
['email', 'trim'],
['email', 'required'],
['email', 'email'],
['email', 'string', 'max' => 30],
['email', 'unique', 'targetClass' => '\common\models\User', 'message' => 'This email address has already been taken.'],
['password', 'required'],
['password', 'string', 'min' => 6],
['first_name', 'trim'],
['first_name', 'required'],
['middle_name', 'trim'],
['middle_name', 'required'],
['last_name', 'trim'],
['last_name', 'required'],
['verifyCode', 'captcha'],
['verifyCode', 'required'],
[['confirmPassword'], 'compare', 'compareAttribute' => 'password', 'message' => 'Passwords do not match.'],
];
}
/**
* Signs user up.
*
* #return User|null the saved model or null if saving fails
*/
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
$user->role = $this->role;
$user->first_name = $this->first_name;
$user->middle_name = $this->middle_name;
$user->last_name = $this->last_name;
return $user->save() ? $user : null;
}
}
This is my controller:
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->renderAjax('signup', [
'model' => $model,
]);
}
I don't have any ideas, I think my codes is correct but i don't know why is not working.
UPDATED
When i clicked the button signup it stay only in the modal and when i clicked it again the button the validations is working. It means it saves to database but not automatically login.
you should get the user identity for login
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
$identity = User::findOne(['username' => $model->$username]);
if (Yii::$app->user->login($identity)) {
return $this->goHome();
}
}
}
return $this->renderAjax('signup', [
'model' => $model,
]);
}
see this for more http://www.yiiframework.com/doc-2.0/guide-security-authentication.html
http://www.yiiframework.com/doc-2.0/yii-web-user.html
I have used below code and its working for me . Its also a standard code for YII2 .Controller Action Code :
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
if ($user = $model->signup()) {
$model= \common\models\User::findOne([$user->id]); //you need to get complete model again and pass it to login function
if (Yii::$app->user->login($model) {
return $this->goHome();
}
}
}
return $this->renderAjax('signup', [
'model' => $model,
]);
}
After couple minutes of step by step debug - it works well
//Signup
public function actionSignup()
{
$model = new SignupForm();
if ($model->load(Yii::$app->request->post()) && $model->signup()) { /*Save
to DB first*/
$genmail = $model->email; //get model email value
$identity = User::findOne(['email' => $genmail]); //find user by email
if (Yii::$app->user->login($identity)) { // login user
return $this->redirect('account'); // show accaount page
}
}
return $this->render('signup', [
'model' => $model,
]);
}

yii2 dynamic form updating only one table

I'm trying to update data with the help of yii2/dynamic form.
Table 1- "sellsg" - columns (ssg_id,ssg_customer,ssg_invoiceno,ssg_date,ssg_amount)
Table2 - "sellitemsg" - columns (ssgi_id,ssgi_invoiceno,ssgi_sgname,ssgi_price)
Relation - sellsg.ssg_invoiceno = sellitemsg.ssgi_invoiceno
The Create part is working fine. I'm struggling with the update part.
Problem 1.
When the form was creating new record - There is a javascript code in the form to increase the invoice no by 1 everytime. When I'm loading the form for update, it also increases in by 1 overriding the original invoiceno. I want to limit this function only when I create but not in update.
Problem 2
When I am updating the form, it only updating the sellsg table but not sellitemsg table.
_Form
<?php
use yii\helpers\Html;
use kartik\form\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use dosamigos\datepicker\DatePicker;
use yii\helpers\ArrayHelper;
use kartik\select2\Select2;
use frontend\modules\sellsg\models\Customer;
use frontend\modules\sellsg\models\Sunglass;
/* #var $this yii\web\View */
/* #var $model frontend\modules\sellsg\models\Sellsg */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="sellsg-form">
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
]);
?>
<div class="row">
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<div class="col-xs-6 col-sm-6 col-lg-6">
<?= $form->field($model, 'ssg_customer')->label(false)->widget(Select2::classname(), [
'data' => ArrayHelper::map(Customer::find()->all(),'c_name','customerDetails'),
'language' => 'en',
'options' => ['placeholder' => 'Select Customer Details', 'id' => 'custid'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'ssg_date')->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 class="col-xs-3 col-sm-3 col-lg-3">
</div>
</div>
</div>
</div>
<?= $form->field($model, 'ssg_invoiceno')->textInput() ?>
<div class="rows">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Sunglasses</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' => $modelsSellitemsg[0],
'formId' => 'dynamic-form',
'formFields' => [
'ssgi_sgname',
'ssgi_price',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsSellitemsg as $i => $modelSellitemsg): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelSellitemsg->isNewRecord) {
echo Html::activeHiddenInput($modelSellitemsg, "[{$i}]ssgi_id");
}
?>
<div class="row">
<div class="col-sm-6">
<?= $form->field($modelSellitemsg, "[{$i}]ssgi_sgname")->label(false)->widget(Select2::classname(), [
'data' => ArrayHelper::map(Sunglass::find()->all(),'sg_name','sg_name'),
'language' => 'en',
'options' => ['placeholder' => 'Select Sunglass'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-sm-3">
<?= $form->field($modelSellitemsg, "[{$i}]ssgi_price")->textInput([
'maxlength' => true,
'class' => 'sumPart',
//'onfocus'=>'sum()', 'onBlur'=>'sum()'
]) ?>
</div>
<div class="col-sm-3">
<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>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-12 col-lg-12">
<div class="form-group">
<div class="col-xs-6 col-sm-6 col-lg-6">
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($model, 'ssg_amount')->textInput(['class' => 'sum']) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-lg-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>
<?php
/* start getting the invoiceno */
$script = <<<EOD
$(window).load(function(){
$.get('get-for-invoiceno',{ invoiceid : 1 }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#sellsg-ssg_invoiceno').attr('value',data.invoiceno);
}
);
});
EOD;
$this->registerJs($script);
/*end getting the invoiceno */
?>
<?php
/* start getting the totalamount */
$script = <<<EOD
var getSum = function() {
var items = $(".item");
var sum = 0;
items.each(function (index, elem) {
var priceValue = $(elem).find(".sumPart").val();
//Check if priceValue is numeric or something like that
sum = parseInt(sum) + parseInt(priceValue);
});
//Assign the sum value to the field
$(".sum").val(sum);
};
//Bind new elements to support the function too
$(".container-items").on("change", ".sumPart", function() {
getSum();
});
EOD;
$this->registerJs($script);
/*end getting the totalamount */
?>
SellsgController
public function actionCreate()
{
$model = new Sellsg();
$modelsSellitemsg = [new Sellitemsg];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$modelsSellitemsg = Model::createMultiple(Sellitemsg::classname());
Model::loadMultiple($modelsSellitemsg, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSellitemsg) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsSellitemsg as $modelSellitemsg) {
$modelSellitemsg->ssgi_invoiceno = $model->ssg_invoiceno;
if (! ($flag = $modelSellitemsg->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ssg_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('create', [
'model' => $model,
'modelsSellitemsg' => (empty($modelsSellitemsg)) ? [new Sellitemsg] : $modelsSellitemsg
]);
}
}
/**
* Updates an existing Sellsg model.
* If update is successful, the browser will be redirected to the 'view' page.
* #param integer $id
* #return mixed
*/
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsSellitemsg = $model->sellitemsg;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsSellitemsg, 'id', 'id');
//var_dump($oldIDs);
$modelsSellitemsg = Model::createMultiple(Sellitemsg::classname(), $modelsSellitemsg);
Model::loadMultiple($modelsSellitemsg, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsSellitemsg, 'id', 'id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSellitemsg) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Sellitemsg::deleteAll(['id' => $deletedIDs]);
}
foreach ($modelsSellitemsg as $modelSellitemsg) {
$modelSellitemsg->ssgi_invoiceno = $model->ssg_invoiceno;
if (! ($flag = $modelSellitemsg->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ssg_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('update', [
'model' => $model,
'modelsSellitemsg' => (empty($modelsSellitemsg)) ? [new Sellitemsg] : $modelsSellitemsg
]);
}
}
sellsg model
<?php
namespace frontend\modules\sellsg\models;
use Yii;
/**
* This is the model class for table "sellsg".
*
* #property integer $ssg_id
* #property string $ssg_customer
* #property integer $ssg_invoiceno
* #property string $ssg_date
* #property integer $ssg_amount
*/
class Sellsg extends \yii\db\ActiveRecord
{
public $modelsSellitemsg;
/**
* #inheritdoc
*/
public static function tableName()
{
return 'sellsg';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['ssg_customer', 'ssg_invoiceno', 'ssg_date', 'ssg_amount'], 'required'],
[['ssg_invoiceno', 'ssg_amount'], 'integer'],
[['ssg_customer'], 'string', 'max' => 200],
[['ssg_invoiceno'], 'unique'],
[['ssg_date'], 'string', 'max' => 10],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'ssg_id' => 'ID',
'ssg_customer' => 'Customer',
'ssg_invoiceno' => 'Invoice No',
'ssg_date' => 'Date',
'ssg_amount' => 'Amount',
];
}
public function getSellitemsg()
{
return $this->hasMany(Sellitemsg::className(), ['ssgi_invoiceno' => 'ssg_invoiceno']);
}
}
update.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model frontend\modules\sellsg\models\Sellsg */
$this->title = 'Update Sellsg: ' . $model->ssg_id;
$this->params['breadcrumbs'][] = ['label' => 'Sellsgs', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->ssg_id, 'url' => ['view', 'id' => $model->ssg_id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="sellsg-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_form', [
'model' => $model,
'modelsSellitemsg' => $modelsSellitemsg,
]) ?>
</div>
With the current code I'm getting error
Getting unknown property: frontend\modules\sellsg\models\Sellitemsg::id
I've found the solution
Problem1 -
I've created _updateform.php and redirected to update from there and removed the javascript to load invoicno -
Update.php
<?php
use yii\helpers\Html;
/* #var $this yii\web\View */
/* #var $model frontend\modules\sellsg\models\Sellsg */
$this->title = 'Update InvoiceNo: ' . $model->ssg_id;
$this->params['breadcrumbs'][] = ['label' => 'Sellsgs', 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $model->ssg_id, 'url' => ['view', 'id' => $model->ssg_id]];
$this->params['breadcrumbs'][] = 'Update';
?>
<div class="sellsg-update">
<h1><?= Html::encode($this->title) ?></h1>
<?= $this->render('_updateform', [
'model' => $model,
'modelsSellitemsg' => $modelsSellitemsg,
]) ?>
</div>
Problem2
My actionUpdate code now looks like -
public function actionUpdate($id)
{
$model = $this->findModel($id);
$modelsSellitemsg = $model->sellitemsg;
//$model->setScenario('update');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$oldIDs = ArrayHelper::map($modelsSellitemsg, 'ssgi_id', 'ssgi_id');
//var_dump($oldIDs);
$modelsSellitemsg = Model::createMultiple(Sellitemsg::classname(), $modelsSellitemsg);
Model::loadMultiple($modelsSellitemsg, Yii::$app->request->post());
$deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsSellitemsg, 'ssgi_id', 'ssgi_id')));
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsSellitemsg) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
if (! empty($deletedIDs)) {
Sellitemsg::deleteAll(['ssgi_id' => $deletedIDs]);
}
foreach ($modelsSellitemsg as $modelSellitemsg) {
$modelSellitemsg->ssgi_invoiceno = $model->ssg_invoiceno;
if (! ($flag = $modelSellitemsg->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->ssg_id]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
}
else {
return $this->render('update', [
'model' => $model,
'modelsSellitemsg' => (empty($modelsSellitemsg)) ? [new Sellitemsg] : $modelsSellitemsg
]);
}
}
/**
* Deletes an existing Sellsg model.
* If deletion is successful, the browser will be redirected to the 'index' page.
* #param integer $id
* #return mixed
*/
public function actionDelete($id)
{
$this->findModel($id)->delete();
return $this->redirect(['index']);
}
and Model.php -
<?php
namespace frontend\modules\sellsg\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, 'ssgi_id', 'ssgi_id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['ssgi_id']) && !empty($item['ssgi_id']) && isset($multipleModels[$item['ssgi_id']])) {
$models[] = $multipleModels[$item['ssgi_id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
And Is working fine now.

Undefined variable: model2

I have 2 models that will load in one form.
But when I want to access the second model, there is error said "Undefined variable: model2"
Please help.
This is the controller
InventoryController.php
public function actionInsert() {
$connection = \Yii::$app->db;
$transaction = $connection->beginTransaction();
$model = new Inventory();
$model2 = new \app\models\Unitofmeasurement();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$command = $connection->createCommand('{call usp_M_Inventory#Transaksi(:ID_Item,:Item_Name, :IDMom, :Item_Price, :ID_InvCategory,:Item_PIC1,
:Item_PIC2,:Item_active, :UserInventory, :ID_Mom, :Satuan_Beli, :Qty_Beli, :Satuan_Jual,:Qty_Jual, :ActiveMOM, :UserMOM)}');
$ID_Item = $model->ID_Item;
$Item_Name = $model->Item_Name;
$IDMom = $model->IDMom;
$Item_Price = $model->Item_Price;
$ID_InvCategory = $model->ID_Inv_Category;
$Item_PIC1 = $model->Item_PIC1;
$Item_PIC2 = $model->Item_PIC2;
$Item_active = $model->Item_active;
$UserInventory = Yii::$app->user->identity->username;
$ID_Mom = $model2->ID_Mom;
$Satuan_Beli = $model2->Satuan_Beli;
$Qty_Beli = $model2->Qty_Beli;
$Satuan_Jual = $model2->Satuan_Jual;
$Qty_Jual = $model2->Qty_Jual;
$ActiveMOM = $model2->Active;
$UserMOM = Yii::$app->user->identity->username;
if ($command->execute() == 0) {
$transaction->commit();
} else {
$transaction->rollBack();
foreach ($model->getErrors() as $key => $message) {
Yii::$app->session->setFlash('error', $message);
}
}
return $this->redirect(['view', 'id' => $model->ID_Item]);
} else {
return $this->render('create', array(
'model' => $model,
'model2' => $model2,
'model3' => $model3,
'model4' => $model4,
'model5' => $model5,
'model6' => $model6,
'model7' => $model7,
));
}
This is Create View
create.php
<h1><?= Html::encode($this->title) ?></h1>
<?=
$this->render('_form', [
'model' => $model,
'model2' => $model2,
'model3' => $model3,
'model4' => $model4,
'model5' => $model5,
'model6' => $model6,
'model7' => $model7,
])
?>
This is the form
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'ID_Item')->textInput() ?>
<?= $form->field($model, 'Item_Name')->textInput() ?>
<?= $form->field($model, 'ID_Mom')->textInput() ?>
<?= $form->field($model, 'Item_Price')->textInput() ?>
<?= $form->field($model, 'ID_Inv_Category')->textInput() ?>
<?= $form->field($model, 'Item_PIC1')->textInput() ?>
<?= $form->field($model, 'Item_PIC2')->textInput() ?>
<?=
$form->field($model, 'Item_active')->widget(SwitchInput::classname(), [
'pluginOptions' => [
'onText' => 'Active',
'offText' => 'Not Active',
]
])
?>
<?=$form->field($model2,'ID_Mom')->textInput() ?>
Your url is: localhost:81/posrkidev/web/index.php/inventory/create
you should put all the code from
public function actionInsert() {
...
}
To action create:
public function actionCreate() {
$connection = \Yii::$app->db;
$transaction = $connection->beginTransaction();
$model = new Inventory();
$model2 = new \app\models\Unitofmeasurement();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$command = $connection->createCommand('{call usp_M_Inventory#Transaksi(:ID_Item,:Item_Name, :IDMom, :Item_Price, :ID_InvCategory,:Item_PIC1,
:Item_PIC2,:Item_active, :UserInventory, :ID_Mom, :Satuan_Beli, :Qty_Beli, :Satuan_Jual,:Qty_Jual, :ActiveMOM, :UserMOM)}');
$ID_Item = $model->ID_Item;
$Item_Name = $model->Item_Name;
$IDMom = $model->IDMom;
$Item_Price = $model->Item_Price;
$ID_InvCategory = $model->ID_Inv_Category;
$Item_PIC1 = $model->Item_PIC1;
$Item_PIC2 = $model->Item_PIC2;
$Item_active = $model->Item_active;
$UserInventory = Yii::$app->user->identity->username;
$ID_Mom = $model2->ID_Mom;
$Satuan_Beli = $model2->Satuan_Beli;
$Qty_Beli = $model2->Qty_Beli;
$Satuan_Jual = $model2->Satuan_Jual;
$Qty_Jual = $model2->Qty_Jual;
$ActiveMOM = $model2->Active;
$UserMOM = Yii::$app->user->identity->username;
if ($command->execute() == 0) {
$transaction->commit();
} else {
$transaction->rollBack();
foreach ($model->getErrors() as $key => $message) {
Yii::$app->session->setFlash('error', $message);
}
}
return $this->redirect(['view', 'id' => $model->ID_Item]);
} else {
return $this->render('create', array(
'model' => $model,
'model2' => $model2,
'model3' => $model3,
'model4' => $model4,
'model5' => $model5,
'model6' => $model6,
'model7' => $model7,
));
}
or try this url: localhost:81/posrkidev/web/index.php/inventory/insert