Form Field Validation

In my application have 2 tables. user and address with fields…

  1. User- user_id, name, age

  2. Address- user_id, city, state

for creating 2 table only Usercontroller used. The form of "User" contain the fields of "Address". like this


<div class="row">

            

		<?php echo $form->labelEx($model,'name'); ?>

		<?php echo $form->textField($model,'name',array('size'=>50,'maxlength'=>50)); ?>

                <?php echo $form->error($model,'name'); ?>

	</div>

      <div class="row">

                <?php echo $form->labelEx(Address::model(), 'city'); ?>

                <?php echo $form->textField(Address::model(), 'city', array('size' => 50, 'maxlength' =>50));>

                <?php echo $form->error(Address::model(), 'city'); ?>

        </div>   



The validation of user table fields worked correctly. but the validation (field is empty, required) for "Address" table not worked. How can add validation to both model form fields?

you should send a model for address to your view




<div class="row">

                <?php echo $form->labelEx($AddressModel, 'city'); ?>

                <?php echo $form->textField($AddressModel, 'city', array('size' => 50, 'maxlength' =>50));>

                <?php echo $form->error($AddressModel, 'city'); ?>

        </div>



read this:

collect data for two or more models

You need to use an actual Address model in your form instead of Address::model().

Obviously, in the controller action that renders that form, you need to pass an Address model and validate it like the way you do with the User model.

Are you have in your form this code? =>


<?php echo $form->errorSummary(array($model,$AddressModel)); ?> 

in the place of $AddressModel in can put other variable name.

Thanks for all rplys… it helps to me.

but the validation for 2nd model fields happends only when click on the textboxes of that model? How solve this?

don’t forget to include the “city” field as required in your address model in your rules array