Sathya Baman
Sathya Baman

Reputation: 3515

Form Not working in YII2

I am new to yii framework.

I have created a from like this. When i try to view the form in the browser like this http://localhost/basic/web/index.php?r=site/user i see a blank white page.

I checked the apache log, No errors logged.

I have added the files to git hub.. https://github.com/sathyabaman/yii_basic_learning

Model

    <?php

    namespace app\models;
    use Yii;
    use yii\base\Model;


    class UserForm extends Model
    {
        public $name;
        public $email;



        public function rules()
        {
            return [

                [['name', 'email'], 'required'],

                ['email', 'email'],

            ];
        }

    }

Controller

 public function actionUser(){

    $model = new UserForm;



    if ($model->load(yii::$app->request->post()) && $model->validate()) {
        echo "string";
        # code...
    }else{
        $this->render('userForm', ['model'=> $model]);
    }
}

Views/Sites

    <?php

    use yii\helpers\Html;
    use yii\widgets\ActiveForm;

    ?>

    <?php $form = ActiveForm::begin(); ?>
    <?= $form->field($model, 'name'); ?>
    <?= $form->field($model, 'email'); ?>

    <?= Html::submitButton('submit', ['class'=>'btn btn-success']); ?>

    <?php $form = ActiveForm::end(); ?>

Can some one help me to fix this problem. Tnx.

Upvotes: 2

Views: 1910

Answers (2)

Andr&#225;s
Andr&#225;s

Reputation: 175

My code was different from this, but the outcome was kind-of the same, I could not load the model from the form. My mistake was I did not have rules for fields in the model - at least "safe" is required to load them - I keep forgetting this. Maybe, this'll help someone else in the future as well. E.g.:

public function rules()
{
    return [
        [['detailed', 'city', 'country'], 'string'],
    ];
}

Upvotes: 0

Dency G B
Dency G B

Reputation: 8146

Add a return before render!

 return $this->render('userForm', ['model'=> $model]);

Upvotes: 2

Related Questions