I just started my first web app with Yii2. Had some problem with active form validation.
In my Model class, i have a set of rule.
ProfileForm.php
class ProfileForm extends Model
{
public $email;
public $lastName;
public $firstName;
public $password;
public $phone;
public $address;
public function rules()
{
return [
[['email', 'firstName', 'lastName', 'address'], 'required'],
];
}
UserController
public function actionUpdateProfile()
{
$model = new ProfileForm();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$user = User::findOne(Yii::$app->user->id);
if ($user != NULL) {
$user->email = $model->email;
$user->firstName = $model->firstName;
$user->lastName = $model->lastName;
$user->address = $model->address;
$user->phone = $model->phone;
$user->save();
}
}
}
public function actionProfile()
{
$model = User::findOne(Yii::$app->user->id);
return $this->render('profile', [
'model' => $model,
]);
}
view profile.php
<?php
$form = ActiveForm::begin([
'id' => 'profile-form',
'action' => ['user/update-profile'],
'options' => [],
'fieldConfig' => [],
]);
?>
<div class="form-group">
<label class="col-sm-3 control-label">First Name</label>
<div class="col-sm-9">
<?= $form->field($model, 'firstName')->textInput([
'placeholder' => $model->attributeLabels()['firstName']
])->label(false) ?>
</div>
</div>
..
..
..
..
<div class="form-group">
<div class="col-sm-offset-3 col-sm-9">
<?= Html::submitButton(Yii::t('app', 'Updated'), ['class' => 'btn btn-default', 'name' => 'profile-button']) ?>
</div>
</div>
<?php ActiveForm::end(); ?>
I want ProfileForm model class to validate the value before updating the actual model class. But the form validation does not trigger when i inserted empty value to fields in the view class.
options' => [], 'fieldConfig' => []- YupikProfiletoUserin a single line i.e$user->attributes=$model->attributes- Muhammad Omer Aslam