Creating Form Error Messages and Rules Without Model

Without creating model how can I create a form which will show custom error messages above the text fields when the fields are left empty ?

Are you also looking to avoid CFormModel?

http://www.yiiframework.com/doc/guide/1.1/en/form.model

Yes. I’m trying to implement javascript validation in Yii without using models. This is how it’s working in .NET




<form method="POST" action="<%=Request.FilePath %>" onsubmit="return validateSellersAndLandLords();" enctype="multipart/form-data">




function validateSellersAndLandLords()

                   { 

                       var firstError = '';

                       var result = true;

                       var obj = document.getElementById("ddlPropertyType");

                       if(obj != null)

                       {

                       

                           if(!(chkEmpty(obj,"property type",'errorddlPropertyType')))

                               {

                                    result = false;

                                    if(firstError=='')

                            {

                                firstError = obj.id;

                            }

                               }                       

                              

                       }


<div id="errorddlPropertyType" class="errordiv" style="display:none;">Please select Property Type.</div>

<div class="enquiry-input-area"><input class="enquiry-input" name="ddlPropertyType" id="ddlPropertyType"  value="<%=Request["ddlPropertyType"]%>" /></div>

When the field is left empty and the form is submitted the errordiv becomes


<div style="display: block;" class="errordiv" id="errorddlPropertyType">Insert property type</div>

Do I really need to use CFormModel to have validation rules ?

I’d say that’s the most sensible way to proceed. It’s much easier to work with the system rather than against it. It’s also designed specifically for creating forms with validation rules.

follow the convention and use a model

I have created model file Landlordrent.php


<?php


class LandlordRent extends CFormModel

{


	public function rules()

	{

		return array(

			array('property, community, building, floor, unit, street, price, view, bedrooms, area, description, contactType, countrycode, areacode, contactNumber, email, country, title, fname, lname', 'required'),

			array('email', 'email'),

		);

	}


	/**

	 * Declares attribute labels.

	 */

	public function attributeLabels()

	{

		return array('email'=>'User Name/Email Address'


		);

	}

}

In controller


public function actionRent()

	{	

	    $model=new Landlordrent;

		

		$countries = Allcountries::model()->findAll(array('order' => 'country ASC'));


		if(isset($_POST['Landlordrent']))

		{

			$model->attributes=$_POST['Landlordrent'];


			if($model->validate())

			{

			$model->save();

			$this->actionIndex();

				// form inputs are valid, do something here

			}

		}

		

		$countries = Allcountries::model()->findAll(array('order' => 'country ASC'));	

		

		$this->render('rent',array('model'=>$model, 'countries'=>$countries));

	}

In loading rent.php view file I’m getting error

<?php echo $form->textField($model, ‘property’, array(“class”=>“enquiry-input”)); ?>

exception ‘CException’ with message 'Property “LandlordRent.property” is

not defined.

C:\wamp\www\yii\framework\web\helpers\CHtml.php(2158)

line 2158 return $model->$attribute;

How do I create attributes in the model file ?

You need to declare any fields as class instance variables. Put


public $property;

at the top of the class, as well as declarations for any other class attributes.

now it’s giving Property “LandlordRent.tableSchema” is not defined.

You’re calling $model->save() in your controller. You can’t do this with CFormModel. If you’re trying to persist to a database table, you should really be using CActiveRecord.

I removed $model->save() but it’s still giving the same error. This is my action


public function actionRent()

	{	

	    $model=new Landlordrent;

		

		$countries = Allcountries::model()->findAll(array('order' => 'country ASC'));


		if(isset($_POST['Landlordrent']))

		{

			$model->attributes=$_POST['Landlordrent'];

		}

		

		$countries = Allcountries::model()->findAll(array('order' => 'country ASC'));

		

		$user = Userregistration::model()->findAll();		

		

		$this->render('rent',array('model'=>$model, 'countries'=>$countries, 'user'=>$user));

	}

Can you post the line of code that the error refers to?

C:\wamp\www\mysite\protected\components\ZHtml.php(16)

preg_match(’/\((.*)\)/’,$model->tableSchema->columns[$attr]->dbType,$matches);

I used Zhtml in another form for populating dropdown with enum fields

The tableSchema property is not going to be available in CFormModel, as it doesn’t link to a database table. Is this ZHtml component a third party tool or something you’ve written yourself?

It’s a third party tool

I’m not sure what to recommend. It seems to assume that you’ll be using active record. Your best bet is to get advice regarding your requirements from the ZHtml class author(s). They can at least advise whether there’s a way to use their tool with CFormModel classes or whether that scenario is simply not supported.

I have to create several form pages which are similar. Do I need to create models for each form ? Can I just use a single model for different but similar forms ?

Can you give an example of the fields on a couple of these forms and the active record models that they correspond to?

Generally, it makes sense to have a single active record class for each table in the database. Depending on the fields your forms contain, you can either:

  • Use a single active record model to build the form (ideal).

  • Use multiple active record models to build a form and persist all of them in a transaction in the controller.

  • Use a CFormModel if the previous option becomes unwieldly or you need complex additional validation.

You should really aim to use active record if you’re intending to persist data to the database.

contact form, website feedback from, enquiry form, offer form, sell property form, buy property form

these forms contain common fileds like title, name, residence, nationality, contact number, email, comments…

How are each of those common fields stored in the database? Does each table contain a copy of them or are they refactored into a separate table?

If you’ve not finished designing the database yet, do that first and the structure of your models will be clearer. In your case, set your models up to match the database tables and consolidate your rules if necessary.

A good way might be to create a validator class for each common field and use that in each active record model that has that field.

Alternatively, create the rule array for each field (storing it somewhere separate) and merge it into the rule array in each active record class.

One other option which you could use if the set of fields is common across several models, is to create a base class with all those fields and their rules, then extend from that in each active record class. This is probably overkill though and doesn’t really fit with the “is-a” concept of classical inheritance.