How Does The Cform Object Handle The Submitted Form?

Hi,

I had read an script from "The Yii book".

protected/controllers/SiteController.php

public function actionContact() {

[indent]$model = new ContactForm;

$form = new CForm(‘application.views.site.contactForm’,

$model);

if ($form->submitted() && $form->validate()) {

// Send the email!

$this->render(‘emailSent’);

} else {

$this->render(‘contact’, array(‘model’ => $model,

‘form’ => $form));

}[/indent]

}

As you can see, the $model and the $form were initially set as an new object.

I am wondering how does the actionContact know the form were submitted via POST method?

And also the page did not render emailSent after I submitted the form.Thanks

Q: POST is the default action for CForm(). It can be changed via one of the options of CForm (sorry not sure which at this time)

Is the if($form->submitted() && $form->validate()) correct? Could it be $model->validate()?

Take a look at the submitted() method.

This will check $_POST for the submitbutton name: default=‘submit’ and will assign the attributes from $_POST if $_POST[‘submit’] isset.

Maybe your button name is not ‘submit’.

Do a var_dump($_POST) or debug to see what values are submitted.

Thanks jkofsky and Joblo,I had solved the issue.

It failed since id did not pass the validation :D

I had another stupid problem now.(Sorry,its my first time using MVC php)

How does the $model know the user post data simply by "$model = new ContactForm"?

I found that it just automatically bind the user provided data to the $model.How?

[indent]public function actionContact() {

$model = new ContactForm;[/indent]

As in procedure programming,there must be an script like:

if(isset($_POST[‘contactform’])){$model->name=$_POST[‘contactform’][‘name’] …}

But I cant find the similar parts in the actionContact.Whats the mechanism underlying?

Thanks.

My advice:

Use a debugger to step through the Yii core or study the Yii source (you can take a quick look in the online documentation).

As I told above, the submitted() method will assign the attributes from $_POST.


submitted($buttonName='submit',$loadData=true)

  • calls

clicked()

to check if the buttonname is submitted

  • calls

loadData()

with


model->setAttributes($_POST[$class]);

The models setAttributes() method (or $model->attributes = …) binds the POST data to the model, but only the safe attributes which a listed in the validation rules() of the model.

Study the tutorials/wiki articles:

For example Working with forms

and the best tutorial - the Yii source: there you will find the answers for all your questions :slight_smile:

AND the attributes that pass validation :)