Working with forms in Yii2.0

Dear all,

I want to create a contact form where customers can ask question on my web site. I think I’m doing everything correct but it seems the relation between my model and my form is not made (I cannot load the form elements in my mode).

Step which I took:

  1. Create model class:



namespace app\models\contact;

use yii\base\Model;




class ContactModel extends Model {


    public $naam;

    public $voornaam;

    public $organisatie;

    public $email;

    public $straat;

    public $nummer;

    public $postcode;

    public $gemeente;

    public $telefoon;

    public $bericht;


    /**

     * @return De validatie regels voor de velden

     */

    public function rules() {

        return [

            // De verplichte velden

            [['naam', 'voornaam','organisatie','email','telefoon'], 'required'],

            ['email','email'],

            ['nummer','number'],

        ];

    }

    

    function getNaam() {

        return $this->naam;

}

//Rest of getters and setters...

    }

Second step2: create view contact form: (using kartik’s widgets)




<?php

        $sendUrl = Url::to(['site/contact']);

        $form = ActiveForm::begin();

        echo FormGrid::widget([

            'model' => $model,

            'form' => $form,

            'autoGenerateColumns' => true,

            'rows' => [

                [

                    'attributes' => [

                        'organisatie' => ['type' => Form::INPUT_TEXT],

                        'naam' => ['type' => Form::INPUT_TEXT],

                        'voornaam' => ['type' => Form::INPUT_TEXT],

                    ],

                ],

                [

                    'attributes' => [

                        'straat' => ['type' => Form::INPUT_TEXT,],

                        'nummer' => ['type' => Form::INPUT_TEXT,],

                        'postcode' => ['type' => Form::INPUT_TEXT,],

                        'gemeente' => ['type' => Form::INPUT_TEXT,],

                    ]

                ],

                [

                    'attributes' => [

                        'telefoon' => ['type' => Form::INPUT_TEXT,],

                        'email' => ['type' => Form::INPUT_TEXT,],

                    ]

                ],

                [

                    'attributes' => [

                        'bericht' => ['type' => Form::INPUT_TEXTAREA, 'options' => ['placeholder' => 'Tekst', 'rows' => '8']],

                    ]

                ],

            ]

        ]);


        echo Html::submitButton('Verstuur bericht', ['type' => 'button', 'class' => 'btn btn-primary',]);

        ActiveForm::end();

        ?>



  1. The code in the controller class:



    public function actionContact() {

        $model = new ContactModel();

        $request = Yii::$app->request;

        $postedForm = $request->post('ContactForm');

        $loaded = $model->load($request->post());

        $validated = $model->validate();

        if ($loaded && $validated) {

            $mail = Yii::$app->mailer->compose();

            $mail->setFrom($model->getEmail());

            $mail->setTo('jens.buysse@hogent.be');

            $mail->setSubject('[Horizon Web Site] : email van '. $model->getOrganisatie());

            $mail->setTextBody($model->getBericht());

            $result = $mail->send();

            if ($result) {

                return $this->render('verstuurd');

            }else{

                return $this->render('error');

            }

        } else {

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

        }

    }



So it seems the ‘load’ method does not load the paramters of the form in my model. How do I do this?

Kind regards

I’ll put a var_dump to check $_POST values and skip email send, so:




    public function actionContact() {

        $model = new ContactModel();

        $request = Yii::$app->request;

        $postedForm = $request->post('ContactForm');

        $loaded = $model->load($request->post());

        $validated = $model->validate();


        // I want check $loaded result and $_POST contents

        var_dump($loaded, $request->post());


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


        /*

        if ($loaded && $validated) {

            $mail = Yii::$app->mailer->compose();

            $mail->setFrom($model->getEmail());

            $mail->setTo('jens.buysse@hogent.be');

            $mail->setSubject('[Horizon Web Site] : email van '. $model->getOrganisatie());

            $mail->setTextBody($model->getBericht());

            $result = $mail->send();

            if ($result) {

                return $this->render('verstuurd');

            }else{

                return $this->render('error');

            }

        } else {

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

        }

        */

    }



This is de dump:


array (size=2)

  '_csrf' => string 'N1UxZ2ROeHcAAEY4F3g.IQUQeApSOj4zeDB8IBYsMAVjPXgtAiEOOg==' (length=56)

  'ContactModel' => 

    array (size=10)

      'organisatie' => string 'test' (length=4)

      'naam' => string 'test' (length=4)

      'voornaam' => string 'test' (length=4)

      'straat' => string 'test' (length=4)

      'nummer' => string 'test' (length=4)

      'postcode' => string 'test' (length=4)

      'gemeente' => string 'test' (length=4)

      'telefoon' => string 'test' (length=4)

      'email' => string 'test' (length=4)

      'bericht' => string 'test' (length=4)

You haven’t post $loaded content.

Check also $model->attributes content to see

if attributes are loaded.

is your namespace correct?




namespace app\models\contact;

is your file under app->models->contact->ContactModel.php?

or is it under app->models->ContactModel.php?

if so your namespace should be


namespace app\models; 

Yes the model is -app\models\contact\ContactModel.php

The output of the dump is the following:




object(app\models\contact\ContactModel)[63]

  public 'naam' => null

  public 'voornaam' => null

  public 'organisatie' => null

  public 'email' => null

  public 'straat' => null

  public 'nummer' => null

  public 'postcode' => null

  public 'gemeente' => null

  public 'telefoon' => null

  public 'bericht' => null

  private '_errors' (yii\base\Model) => 

    array (size=0)

      empty

  private '_validators' (yii\base\Model) => 

    object(ArrayObject)[64]

  private '_scenario' (yii\base\Model) => string 'default' (length=7)

  private '_events' (yii\base\Component) => 

    array (size=0)

      empty

  private '_behaviors' (yii\base\Component) => 

    array (size=0)

      empty



and




array (size=2)

  '_csrf' => string 'SWpHVlh3b0kjGwwFNhFCKnszDTwAKFYROFsdGz0VHH0BKyE0KAI/EA==' (length=56)

  'ContactModel' => 

    array (size=10)

      'organisatie' => string 'test' (length=4)

      'naam' => string 'test' (length=4)

      'voornaam' => string 'test' (length=4)

      'straat' => string 'test' (length=4)

      'nummer' => string '33' (length=2)

      'postcode' => string 'test' (length=4)

      'gemeente' => string 'test' (length=4)

      'telefoon' => string '0479' (length=4)

      'email' => string 'test@email.com' (length=14)

      'bericht' => string 'test' (length=4)



Come back to original code.




    public function actionContact() {

        $model = new ContactModel();

        $request = Yii::$app->request;

        $postedForm = $request->post('ContactForm');

        $loaded = $model->load($request->post());

        $validated = $model->validate();

        if ($loaded && $validated) {

            $mail = Yii::$app->mailer->compose();

            $mail->setFrom($model->getEmail());

            $mail->setTo('jens.buysse@hogent.be');

            $mail->setSubject('[Horizon Web Site] : email van '. $model->getOrganisatie());

            $mail->setTextBody($model->getBericht());

            $result = $mail->send();

            if ($result) {

                return $this->render('verstuurd');

            }else{

                return $this->render('error');

            }

        } else {

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

        }

    }



From $_POST seems that $_POST[‘ContactModel’] is filled.

But code in “if ($loaded && $validated) { … }” isn’t executed, so?

Change previous to




    public function actionContact() {

        $model = new ContactModel();

        $request = Yii::$app->request;

        $postedForm = $request->post('ContactForm');

        $loaded = $model->load($request->post());

        $validated = $model->validate();


        // --- data to check

        var_dump($loaded, $validated, $model->attributes, $request->post());


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


        /*

        if ($loaded && $validated) {

            $mail = Yii::$app->mailer->compose();

            $mail->setFrom($model->getEmail());

            $mail->setTo('jens.buysse@hogent.be');

            $mail->setSubject('[Horizon Web Site] : email van '. $model->getOrganisatie());

            $mail->setTextBody($model->getBericht());

            $result = $mail->send();

            if ($result) {

                return $this->render('verstuurd');

            }else{

                return $this->render('error');

            }

        } else {

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

        }

        */

    }



Post var_dump output (that display "$loaded, $validated, $model->attributes, $request->post()" values) after second call (first call is to load form, second call receive data from form).

seriously ? does no one read the documentation ?

http://www.yiiframework.com/doc-2.0/yii-base-model.html#load()-detail

seems you will need to pass in the name of the form to the load call