Yii2 save model to database - php

I'm trying to do simple CRUD application with Yii2, but when I'm trying to save data, no validation errors appears and $model->validate() returns false. Here's my code:
public function actionCreate()
{
$model = new Game();
if($model->load(Yii::$app->request->post()) && $model->save())
{
$this->redirect(['game-list']);
}
return $this->render('create', ['model' => $model]);
}
So, $model->load() returns true and here is my rules() in my model:
public function rules()
{
return [
[['title', 'subtitle', 'description'], 'required'],
[['id_type', 'is_active', 'picture'], 'default'],
];
}
I have seven columns in DB (this 6 + id as a primary key). I will be glad if anyone help me.
UPD:
View:
<? $form = ActiveForm::begin(array('options' => array('class' => 'form-horizontal'))); ?>
<?= $form->errorSummary($model); ?>
<?= $form->field($model, 'title')->textInput(); ?>
<?= $form->field($model, 'subtitle')->textInput(); ?>
<?= $form->field($model, 'description')->textInput(); ?>
<div class="form-actions">
<?= Html::submitButton(Yii::t('app', $model->isNewRecord ? 'Create' : 'Update')); ?>
</div>
<? ActiveForm::end(); ?>

My mistake was obviously stupid, but here it is. I've created method beforeSave in my model and haven't filled it and totally forgot about it's existence. So, 'cause it's not returned true - validate() cannot pass properly. Sorry for wasted time.

Related

How to get value of attribute in controller from Form in view Yii 2

I created a table named (users) it has two columns: name and pass.
In view I created form like this:
<?php
$form = ActiveForm::begin() ?>
<div class="form-group">
<?= $form->field($model, 'user') ?>
<?= $form->field($model, 'password') ?>
<div class="col-lg-offset-1 col-lg-11">
<?= Html::submitButton('Login', ['class' => 'btn btn-primary']) ?>
</div>
</div>
<?php ActiveForm::end() ?>
So I need to pass this two attributes to controller to insert into data base.
In YourController.php
assuing you have an Create action for manage your insert in db
and a create view for manage the user input (a view for only display the correct result )
<?php
namespace app\controllers;
use Yii;
use yii\web\Controller;
use app\models\EntryForm;
class YourController extends Controller
{
// ...existing code...
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
// valid data received in $model
//
if( $model->save()){
return $this->render('create', ['model' => $model]);
} else {
// this is just for debug
var_dump('not inserted');
die();
}
} else {
// either the page is initially displayed or there is some validation error
return $this->render('view', ['model' => $model]);
}
// render the initial page per allow to the user input
return $this->render('create', ['model' => $model]);
}
....
}
In your controller you can get your post form in this way:
Yii::$app->request->post()
And this way you can load the value into your model
$model->load(Yii::$app->request->post())
Here you can find a starting point

Yii2 Controller post request is NULL

Can anyone tell why controller post in database is NULL ?
but in vardump have data
Controller
$model = new Reg();
$model->load(\Yii::$app->request->post());
$model->save();
Model
public function rules()
{
return [
[['title', 'article', 'fio','country', 'position','tel', 'email','cert'], 'required', 'message'=>'required'],
[['title', 'article', 'fio','country', 'position','tel', 'email','cert'], 'string'],
[['title', 'article'], 'safe'],
];
}
View
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?php echo $form->field($model,'title')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'article')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'fio')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'country')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'position')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'tel')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'email')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php echo $form->field($model,'cert')->textInput(['class'=>'header__enter__input','placeholder'=>''])->label(false) ?>
<?php ActiveForm::end() ?>
ActiveRecord insert data to db when model validate() returned true. If this error occured for model attributes validating and validate() method returned false post data wil not insert to db for view error you can use change the controller to this
$model = new Reg();
if($model->load(Yii::$app->request->post()) && $model->validate() && $model->save()){
return $this->redirect(['index']);
}
return $this->render('create', ['model' => $model]);
}
and you can view errors in validate or not and fix this
$model->save(false);
will save your data forcefully by skipping validation but it is bad practice,
use $model->getErrors() after save, It will return list of validation errors which prevent data from storing from database

inserting values for each of items of an enum field using Yii2 activeform

I have a user model and an attachment model.
User:
id name email password_hash
--------------------------------------
1 Reza reza#web.af xxxxxxx
Attachment:
user_id type(enum) name
--------------------------------------
1 resume fk4k34kdfmkg3.pdf
1 photo 59rg3kerfn3ju.jpg
1 nid 34kf2wkefclh0.jpg
I need to create the activeform for it and I am wondering what is the appropriate (best) way to create model fields for them. each time a new user is registered three rows of attachments will be inserted to the attachments table too. Of course the following activeform is not doing what i want. please help.
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($user, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'email')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($attachment, 'type')->fileInput()->label('photo') ?>
<?= $form->field($attachment, 'type')->fileInput()->label('resume') ?>
<?= $form->field($attachment, 'type')->fileInput()->label('nid') ?>
..
..
In your model define three public variable like
public $typePhoto;
public $typeResume;
public $typeNid;
then define rules like
public function rules()
{
return [
[['typePhoto', 'typeResume', 'typeNid'], 'required'],
];
}
and then create ActiveForm like this
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($user, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'email')->textInput(['maxlength' => true]) ?>
<?=$form->field($user, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($attachment, 'typePhoto')->fileInput()->label('photo') ?>
<?= $form->field($attachment, 'typeResume')->fileInput()->label('resume') ?>
<?= $form->field($attachment, 'typeNid')->fileInput()->label('nid') ?>
..
..
Refer Creating Forms
I think for that purpose you should use yii model form extended from yii\base\Model. It can provide columns different from database ones.
Here is the simplified example of form model that you need:
class LoginForm extends \yii\base\Model
{
public $name;
public $email;
public $password_hash;
public $type_resume;
public $type_photo;
public $type_nid;
public function rules()
{
return [
// define validation rules here
];
}
public function saveData()
{
$userModel = new User();
$userModel->name = $this->name;
//and so on, save all user properties
$userModel->save();
$attachModel = new Attachment();
$attachModel->type = 'resume'; //it better to use constant
$attachModel->user_id = $userModel->id;
$attachModel->name = ' '; //set the necessary value
$attachModel->save();
//and so on, save your attachment models for all types
}
}
So your ActiveForm should be something like this:
<?php $form = ActiveForm::begin(); ?>
<?=$form->field($loginForm, 'name')->textInput(['maxlength' => true]) ?>
<?=$form->field($loginForm, 'email')->textInput(['maxlength' => true]) ?>
<?=$form->field($loginForm, 'password_hash')->passwordInput(['maxlength' => true]) ?>
<?= $form->field($loginForm, 'type_photo')->fileInput()->label('photo') ?>
<?= $form->field($loginForm, 'type_resume')->fileInput()->label('resume') ?>
<?= $form->field($loginForm, 'type_nid')->fileInput()->label('nid') ?>
..
In code above the $loginForm is object of LoginForm class. Use saveData method of LoginForm to save the data properly.
For more information about yii form models visit http://www.yiiframework.com/doc-2.0/guide-input-forms.html

How to display success message if users was added to the database in Yii2?

I know this is a dumb question, but I just started learning with Yii2. I haven't found any useful information here related to this, so. What I need to do is display a message if the user was added to the database successfuly. Could somoene help me to solve this? I've no idea where it has to be written: in a model, controller or view.
Here is my controller action:
public function actionCreate()
{
$model = new Employee();
$model->scenario = Employee::SCENARIO_CREATE;
$post = Yii::$app->request->post();
if ($model->load($post) && $model->save()) {
return $this->redirect(['create']);
}
return $this->render('create', [
'model' => $model,
]);
}
Here is my view:
<div class="employee-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput([
'maxlength' => 50,
]) ?>
<?= $form->field($model, 'surname')->textInput([
'maxlength' => 50,
]) ?>
<?= $form->field($model, 'employment_date')->textInput() ?>
<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>
Now what is happening is that the script doesn't allow to enter the date, which is later than today's date and also doesn't allow to enter a string into the date field. So to be clear, if the user has entered correct information, I need to add the message that would say "Users has been entered to the database successfully".
Thanks for any help!
Set flash message in your controller. like below.
Yii::$app->session->setFlash('flashMsg', 'flash Msg or any kind of content like variables');
and show this message in your view page. like below.
<?php if (Yii::$app->session->hasFlash('flashMsg')){ ?>
<div class="alert alert-success">
<!-- flash message -->
<?php Yii::$app->session->getFlash('flashMsg'); ?>
</div>
<?php } ?>
You can use the Yii::$app->session->setFlash method in your controller with no need to add anything in the view:
public function actionCreate()
$model = new Employee();
$model->scenario = Employee::SCENARIO_CREATE;
$post = Yii::$app->request->post();
if ($model->load($post) && $model->save()) {
Yii::$app->session->setFlash('success', 'User added');
return $this->redirect(['create']);
}
else {
Yii::$app->session->setFlash('error', 'Error adding user');
}
return $this->render('create', [
'model' => $model,
]);
}

Cannot load form yii2

I am newbie to yii2. I am trying to create my simple form in yii2 to retrieve password. Here is class code:
<?php
namespace app\models;
use yii\base\Model;
class RetrievePasswordForm extends Model
{
public $email;
public function rules()
{
return [
['email', 'required'],
['email', 'email'],
];
}
}
Here is action code:
$model = new RetrievePasswordForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()){
return $this->render('retrievepassword-confirm', ['model' => $model]);
} else {
return $this->render('retrievepassword', ['model' => $model]);
}
My form looks like this:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$this->title = 'Retrieve password';
$this->params['breadcrumbs'][] = $this->title;
?>
<h1><?= Html::encode($this->title) ?></h1>
<p>We will send link to retrieve your password to the following email:</p>
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'email')->textInput(['style'=>'width:200px'])?>
<div class="form-group">
<?= Html::submitButton('Send', ['class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
The problem is that $model->load(Yii::$app->request->post()) always returns false, so when I am clicking "submit" button, page just reloads.
I am currently working without database. I am just creating form and trying to go to another form, when valid data received in model. Thanks for help.
Try explicitally assign the method and the action to the active Form
Then Assuming that your target action is named actionRetrivePassword
<?php $form = ActiveForm::begin([
'method' => 'post',
'action' => Url::to(['/site/retrivepassword']
); ?>
I'll go with I feel it's wrong, if this doesn't help, please give more information.
It's a registration form, so I assume you need email and password for that (since you have those columns in database). But you also declared public member $email in your model. This removes any value associated to $email from database. Therefore, remove this line:
public $email;

Categories