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
Related
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);
}
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,
]);
}
I am getting frusted because the edit.ctp is not recognizing the stored data within a multible value checkbox. This is my code:
Controller:
public function edit($id = null) {
$this->set('userfunc', $this->Auth->user('userfunction_id'));
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->data);
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
}
**$selection = explode('#',$user->member);**
$userfunctions = $this->Users->Userfunctions->find('list', ['limit' => 200]);
$userappartments = $this->Users->Userappartments->find('list', ['limit' => 200]);
$userparkings = $this->Users->Userparkings->find('list', ['limit' => 200]);
$this->set(compact('user', 'userfunctions', 'userappartments', 'userparkings', 'selection'));
$this->set('_serialize', ['user']);
}
edit.ctp:
<?php
echo $this->Form->label('User.status', 'Status');
$options = $statusList;
echo $this->Form->radio('status', $statusList);
echo $this->Form->label('User.member', 'Mitglied');
echo $this->Form->input('member', ['options' => $memberList, 'multiple' => 'checkbox', 'label' => false, 'selected' => $selection]);
echo $this->Form->input('userappartment_id', ['options' => $userappartments, 'label' => 'Wohnung']);
echo $this->Form->input('userparking_id', ['options' => $userparkings, 'label' => 'Parkplatz']);
echo $this->Form->input('contact', ['label' => 'Kontakt']);
?>
================
print_r is displaying an array that looks fine:
enter image description here
but the field in the form is emty:
enter image description here
I've learned a little bit about yii2 framework, but I've got an error which I can't solve. I'm trying to add a image to signup form.
view:
<?php $form = ActiveForm::begin(['id' => 'form-signup', 'options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'voornaam')->textInput(['autofocus' => true]) ?>
<?= $form->field($model, 'bedrijf') ?>
<?= $form->field($model, 'telefoon') ?>
<?= $form->field($model, 'username')?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, 'file')->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
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->render('signup', [
'model' => $model,
]);
}
model:
public function signup()
{
if (!$this->validate()) {
return null;
}
$user = new User();
$imageName = $user->username;
$user->file = UploadedFile::getInstance($user,'file');
$user->file->saveAs( 'uploads/'.$imageName.'.'.$model->file->extension );
$user->picture = 'uploads/'.$imageName.'.'.$model->file->extension;
$user->voornaam = $this->voornaam;
$user->bedrijf = $this->bedrijf;
$user->telefoon = $this->telefoon;
$user->username = $this->username;
$user->email = $this->email;
$user->setPassword($this->password);
$user->generateAuthKey();
return $user->save() ? $user : null;
}
I'm getting the error:
Call to a member function saveAs() on null
What did I do wrong?
(I'm using the advanced template).
you should use $this instead of $user or you should add
$user=$this
because simply $user is new instance and it's field are empty !
It looks like you are mentioning wrong file path, you must mention rootpath for save function
for example
$user->file->saveAs(\Yii::getAlias('#webroot').'/uploads/'.$imageName.'.'.$model->file->extension );
I used separate upload function to upload a file and it's worked.
my view
<?php $form = ActiveForm::begin(['id' => 'form-signup','options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'username') ?>
<?= $form->field($model, 'email') ?>
<?= $form->field($model, 'password')->passwordInput() ?>
<?= $form->field($model, "files")->fileInput() ?>
<div class="form-group">
<?= Html::submitButton('Signup', ['class' => 'btn btn-primary', 'name' => 'signup-button']) ?>
</div>
<?php ActiveForm::end(); ?>
controller
public function actionSignup() {
$model = new SignupForm();
if ($model->load(Yii::$app->request->post())) {
$model->files = \yii\web\UploadedFile::getInstance($model,'files');
if ($model->upload() && $user = $model->signup()) {
if (Yii::$app->getUser()->login($user)) {
return $this->goHome();
}
}
}
return $this->render('signup', [
'model' => $model,
]);
}
and my model is
//declare variable
public $files;
//add this to your rules
[['files'], 'file', 'skipOnEmpty' => false, 'extensions' => 'png, jpg, jpeg']
//File upload function
public function upload()
{
if ($this->validate()) {
$this->files->saveAs('../web/uploads/' . $this->files->baseName. '.' .$this->files->extension);
$this->picture = '../web/uploads/' . $this->files->baseName. '.' .$this->files->extension;
return true;
} else {
return false;
}
}
public function signup()
{
$user = new User();
$user->username = $this->username;
$user->email = $this->email;
$user->picture = $this->picture;
$user->setPassword($this->password);
$user->generateAuthKey();
if ($user->save()) {
return $user;
}
else{
return null;
}
}
Just sharing you my solution, change the path to uploads folder to ../uploads/
In your model try changing saveAs function as shown below
$user->file->saveAs( '../uploads/'.$imageName.'.'.$model->file->extension );
I am a beginner in yii2, I faced a problem when i tried the file upload code from
https://www.yiiframework.com/doc/guide/2.0/en/input-file-upload,
this solved my problem
This is my view file:
<?php
$data = array();
echo '<label class="control-label">Attribute Group Name</label>';
echo Select2::widget([
'name' => 'attribute_grp_name',
'data' => $attribute_group_name, // initial value
'options' => ['placeholder' => 'Please Enter Attribute Group Name', 'multiple' => true],
'pluginOptions' => [
'attribute_grp_name' => true,
'maximumInputLength' => 100,
],
]);
?>
In my view here selected data is not showing.
This is my controller for create and update function:
public function actionCreate()
{
$model = new AttributeSet();
$attribute_group = AttributeGroupLang::find()->select('*')->all();
$attribute_group_name = ArrayHelper::map($attribute_group, 'id_attribute_group', 'name');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('create', [
'model' => $model,
'attribute_group_name' => $attribute_group_name,
]);
}
}
This is update function:
public function actionUpdate($id)
{
$model = $this->findModel($id);
$attribute_set_group_combination = AttributeSetGroupCombination::find()->where(['id_attribute_set' => $id])->all();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$post_array = Yii::$app->request->post();
if(!empty($post_array['attribute_grp_name'])){
AttributeSetGroupCombination::deleteAll('id_attribute_set = '.$id);
foreach ($post_array['attribute_grp_name'] as $key => $value) {
$attribute_set_group_combination = new AttributeSetGroupCombination();
$attribute_set_group_combination->id_attribute_set = $model->id_attribute_set;
$attribute_set_group_combination->id_attribute_group = $value;
$attribute_set_group_combination->save(false);
}
}
return $this->redirect(['view', 'id' => $model->id_attribute_set]);
} else {
return $this->render('update', [
'model' => $model,
'attribute_set_group_combination' => $attribute_set_group_combination,
'attribute_group_name' => $this->getExistAttrSet($id),
]);
}
}
public function getExistAttrSet($id){
$query = new Query;
$query->select(['attribute_group_lang.name AS attribute_group_name','attribute_group_lang.id_attribute_group'])
->from('attribute_set_group_combination')
->join('LEFT OUTER JOIN', 'attribute_set', 'attribute_set.id_attribute_set =attribute_set_group_combination.id_attribute_set')
->join('LEFT OUTER JOIN', 'attribute_group_lang', 'attribute_group_lang.id_attribute_group =attribute_set_group_combination.id_attribute_group')
->where('attribute_set.id_attribute_set='.$id)
->all();
$command = $query->createCommand();
$model = $command->queryAll();
$data = array();
foreach ($model as $attrsetlist[]) {
$data = ArrayHelper::map($attrsetlist, 'id_attribute_group', 'attribute_group_name');
}
return $data;
}
Can anyone help me that how can i show the selected value in the multiple select field.
You just need to pass in model value:
<?php
echo kartik\select2\Select2::widget([
'name' => 'some_field_name',
// ----------------------
'value' => 'a',
//'value' => ['a', 'b'],
//'value' => $model->some_value,
// ----------------------
'data' => ['a'=>'a', 'b'=>'b', 'c'=>'c'],
'options' => ['placeholder' => 'Select menu items ...', ],
]);
?>