Reputation: 205
I created CRUD in Yii2. I used class extend Model and i think i do all right but when i tried to validate my data i get errors that attributes cannot be blanc. When i dont used validate my aplication save data to datatable corretly. This is my action create and update in controller:
public function actionCreate()
{
$model = new UrUserForm();
$model->scenario = 'create';
var_dump($model->validate(), $model->getErrors());
exit();
if ($model->load(Yii::$app->request->post())&& $model->saveUser()) {
Yii::$app->session->setFlash('success', 'Użytkownik został dodany');
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
public function actionUpdate($id)
{
$model = UrUserForm::findOne($id);
if (!$model) {
Yii::$app->session->setFlash('error', 'Niestety wystąpił błąd. Przosze skontaktować się z administratorem');
return $this->redirect(['index']);
}
$model->scenario = 'update';
if ($model->load(Yii::$app->request->post()) && $model->updateUser()) {
Yii::$app->session->setFlash('success', 'Dane zostały zapisane');
return $this->redirect(['index']);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
I wrote var_dump() above in create action, to check whether the data are and when i filled all my inputs i have this message:
bool(false) array(7) { ["Login"]=> array(1) { [0]=> string(22) "Login cannot be blank." } ["Sex"]=> array(1) { [0]=> string(23) "PĹeÄ cannot be blank." } ["Name"]=> array(1) { [0]=> string(22) "ImiÄ cannot be blank." } ["Surname"]=> array(1) { [0]=> string(25) "Nazwisko cannot be blank." } ["BirthDate"]=> array(1) { [0]=> string(31) "Data urodzenia cannot be blank." } ["Email"]=> array(1) { [0]=> string(22) "Email cannot be blank." } ["Password"]=> array(1) { [0]=> string(23) "HasĹo cannot be blank." } }
When i delete var_dump it save corretly but i know i should validate this data. There is my UrUserForm:
<?php
namespace backend\modules\users\models;
use common\models\User;
use backend\modules\users\models\UrUser;
use yii\base\Model;
use Yii;
use yii\helpers\Url;
class UrUserForm extends Model {
public $Login;
public $Email;
public $Password;
public $Sex;
public $Country;
public $Language;
public $Category;
public $AccoutType;
public $Name;
public $Surname;
public $BirthDate;
public $RulesAccept;
public $user;
public function rules() {
return [
[['Country', 'Language', 'Category'], 'safe'],
['Login', 'filter', 'filter' => 'trim'],
[['Login', 'Sex', 'Name', 'Surname', 'BirthDate'], 'required'],
['Login', 'unique', 'targetClass' => '\common\models\User', 'message' => Yii::t('app', 'Pdany login jest już używany')],
['Login', 'string', 'min' => 2, 'max' => 255],
['Email', 'filter', 'filter' => 'trim'],
['Email', 'required'],
['Email', 'email'],
['Email', 'string', 'max' => 255],
['Email', 'unique', 'targetClass' => '\common\models\User', 'message' => Yii::t('app', 'Podany e-mail jest już używany')],
['Password', 'string', 'min' => 6],
['Password', 'required','on' => 'create'],
];
}
public function saveUser() {
$user = new UrUser();
$user->Login = $this->Login;
$user->Email = $this->Email;
$user->RulesAccept = 1;
$user->Rel_Sex = $this->Sex;
$user->Name = $this->Name;
$user->BirthDate = $this->BirthDate;
$user->Surname = $this->Surname;
$user->setPassword($this->Password);
$user->generateAuthKey();
$user->Rel_Country = $this->Country;
$user->Rel_UserCategory = $this->Category;
$user->Rel_Language = $this->Language;
$user->status = 10;
$this->user = $user;
$user->created_at=time();
if ($this->validate() && $user->validate()) {
$user->save();
return $user;
}
return false;
}
public function updateUser() {
$this->user->load($this->toArray(), '');
$this->user->Rel_Country=$this->Country;
$this->user->Rel_Language=$this->Language;
$this->user->Rel_UserCategory=$this->Category;
$this->user->Rel_Sex=$this->Sex;
$this->user->updated_at=time();
if (!empty($this->Password)) {
$this->user->setPassword($this->Password);
}
return $this->user->save();
}
public static function findOne($id) {
$user = UrUser::find()->where(['Id' => $id])->one();
$model = new UrUserForm();
$model->load($user->toArray(), '');
$model->Country=$user->Rel_Country;
$model->Language=$user->Rel_Language;
$model->Category=$user->Rel_UserCategory;
$model->scenario = 'update';
$model->Sex=$user->Rel_Sex;
$model->user = $user;
return $model;
}
}
And this is form:
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use common\models\SmCountry;
use common\models\SmSex;
use common\models\SmLanguage;
use common\models\SmUserCategory;
use yii\helpers\ArrayHelper;
use kartik\date\DatePicker;
/* @var $this yii\web\View */
/* @var $model backend\modules\users\models\UrUser */
/* @var $form yii\widgets\ActiveForm */
?>
<div class="ur-user-form">
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'Sex')->radioList(array('1' => Yii::t('app', 'Mężczyzna'), 2 => Yii::t('app', 'Kobieta'))); ?>
<?= $form->field($model, 'Name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Surname')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Login')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'Email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'BirthDate')->widget(DatePicker::classname(), ([
'pluginOptions' => [
'language' => 'pl',
'format' => 'yyyy-mm-dd',
'todayHighlight' => true,
'autoclose' => true,
]
])) ?>
<label class="control-label"> <?= Yii::t('app', 'Hasło')?> </label>
<?= $form->field($model, 'Password')->passwordInput(['placeholder' => Yii::t('app', 'Utwórz hasło'), 'value' => ''])->label('') ?>
<label class="control-label"> <?= Yii::t('app', 'Państwo')?> </label><br>
<?= Html::activeDropDownList($model, 'Country', ArrayHelper::map(SmCountry::find()->all(), 'Id', 'Name'), ['prompt' => 'Wybierz państwo'])?>
<br><label class="control-label"> <?= Yii::t('app', 'Język')?> </label><br>
<?= Html::activeDropDownList($model, 'Language', ArrayHelper::map(SmLanguage::find()->all(), 'Id', 'Name'), ['prompt' => 'Wybierz język'])?>
<br><label class="control-label"> <?= Yii::t('app', 'Kategoria')?> </label><br>
<?= Html::activeDropDownList($model, 'Category', ArrayHelper::map(smUserCategory::find()->all(), 'Id', 'Name'), ['prompt' => 'Wybierz kategorię'])?>
<div class="form-group">
<?= Html::submitButton(Yii::t('app', 'Dodaj'), ['class'=> 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</
div>
I dont know why i have this error when i want to validate my data anyone can help me?
Upvotes: 0
Views: 772
Reputation: 683
Attributes are empty because you're dumping before loading them into your model instance.
Try $model->load(Yii::$app->request->post())
first. Then you could properly use the methods $model->validate()
and $model->save()
.
Upvotes: 1