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:
- 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();
?>
- 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