What’s with a YII Framework Form Model

There are a lot of times when you build a form that have fields that do not translate into database fields. A simple example is a contact form.

Commonly, you would have the following fields in a contact form:

  • Name
  • Email
  • Subject
  • Message

And most of the time, you don’t need a database table for that. How would you validate a form in a framework that has validations in the model?

The CFormModel is Yii Framework’s answer to this. The CFormModel you can accept user input data and validate for you. But it does not relate to any data in the database.

The CFormModel works just like most things in Yii. You will need just need to extend the CFormModel:

class ContactForm extends CFormModel {
}

Now we would need properties that will relate to things we would want to validate. In our case we would need, name, email, subject and message.

public $name;
public $email;
public $subject;
public $message;

Now we would need to add our validation rules:

public function rules()
{
    return array(
        array('name, email, subject, message', 'required'),
        array('email', 'email'),
        array('message, subject', 'length', 'min' => 20)
    );
}

Now in the controller, you will need to pass the form model to the view for us to use it in the view.

$contact_form_model = new ContactForm;
$this->render('contact_form', array('contact_form_model' => $contact_form_model));

When you accept a POST from the client, you can validate the form via:

if ($_POST)
{
    $contact_form_model->attributes = $_POST['ContactForm'];
    if ($contact_form_model->validate())
    {
        // do your stuff
    }
}

It is really important that you instantiate the model before you validate() because if you instantiate it on the render portion, you’d lose any validation done before it including any validation errors from a POST.

Here is a complete controller method with accepting and validating a POST:

$contact_form_model = new ContactForm;
if ($_POST)
{
    $contact_form_model->attributes = $_POST['ContactForm'];
    if ($contact_form_model->validate())
    {
        // do your stuff
    }
}
$this->render('contact_form', array('contact_form_model' => $contact_form_model));

Advertisements