How to Add Model To Controller

I’m new to MVC, moreover to Yii. I’ve got this script that asks for address first before proceeding to a new set of forms. the controller has this




<?php


namespace app\controllers;

use Yii;


class AddressController extends \yii\web\Controller

{

    public function actionIndex()

    {

        $data = Yii::$app->request->get();

        if (isset($data['address'])) {

            $address = $data['address'];

            Yii::$app->session['address'] = $address;

        }

        else {

            $address = "";

            Yii::$app->session['address'] = '';

			}


        return $this->render('index',["address"=>$address]);

    }


}



The form looks like this (below), the field is autocompleting using Google Places API




<form action="#" class="header_form clearfix">

<input type="text" placeholder="Enter your address" id="autocomplete" onFocus="//geolocate()">

<a href="" class="btn" onclick="document.location='/address?address='+$('#autocomplete').val();return false;">Check Address</a>

</form>



I searched everywhere and it doesn’t have a ‘model’ on model directory where i could add a validation.

Can anyone help how can i make the field validate with error and make sure it has the ‘address’ first before continuing to the next form?

Any help will be appreciated

You should wrap data inside a model, so you can use all support about validation provided from framework.

Firstly, create the model.




<?php

namespace app\models;


use yii\base\Model;

use Yii;


/**

 * Signup form

 */

class MyFormModel extends Model

{

    public $address;


    /**

     * @inheritdoc

     */

    public function rules()

    {

        return [

            [['address'], 'required'],

        ];

    }


    public function attributeLabels()

    {

        return [

            'address' => 'Address',

        ];

    }


}



Then change index action code in:




    public function actionIndex()

    {

        $model = new \app\models\MyFormModel();

        $model->load(\Yii::$app->request->post());

        if($model->validate())

        {

            Yii::$app->session['address'] = $model->address;

        }

        else {

            Yii::$app->session['address'] = '';

        }


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

    }



Finally, change the code in the view:




<?php $form = \yii\widgets\ActiveForm::begin(['id' => 'my-form']); ?>


<?= $form->field('model', 'address')->textInput(['onFocus' => '//geolocate()']); ?>

<?= Html::button('Check address'), ['class' => 'btn']) ?>

			        

<?php \yii\widgets\ActiveForm::end(); ?>



Thanks a lot Fabrizio! that works Fabriziolously! :)