Generate unique ID attributes for Input fields

<?php foreach($models as $model) { ?>

	<?php echo CHtml::activeLabel($model, 'title'); ?>

	<?php echo CHtml::activeTextField($model, 'title', array('size'=>45)); ?>

<?php } ?>

This outputs a label and a textfield for several records on the same page. The problem here is that the label ‘FOR’ and input ‘ID’ attributes are exactly the same.

How can I generate unique IDs (and associated label FOR attributes)?

By the way I noticed CHTML has a property ‘count’ - integer - the counter for generating automatic input field names. Is this what I need and if so how do I use it?

No, you should collect tabular input.

There is no meaninigs in create 2 textbox with the same name, as the you will only get the value of the last one.

Tabular input cames for solve this kind of problems.

Thanks for that boss, I did not know about that trick :)

Yeah!! If you want there is an extension for manage this tabular input.

Is a bit complicated, but I guess it worth.

I’d be peased if you will give a try and give some feedback!

I will defintely give that a try when I get some free time.

I’m currently having a slight problem with this - when I submit the form only the first model is being validated:

<?php foreach($models as $i=>$model) { ?>

	<?php echo CHtml::activeLabelEx($model, "[$i]title"); ?>

	<?php echo CHtml::activeTextField($model, "[$i]title", array('size'=>45)); ?>

<?php } ?>

public function actionUpdate()


	$models=Content::model()->findAll('user_id=:user_id', array(':user_id'=>Yii::app()->user->id));





		foreach($models as $i=>$model)







			$valid=$valid && $model->validate();




			// something here




	$this->render('update', array(




I really advice to take a look to the extension, you are rewriting the same code (it will be more time saving using alread written code).

For your problem you should use:

      $valid=$model->validate() && $valid;

Php is lazy, if $valid is false is not evaluating the second part of the &&, so you miss the validation.

Thanks again boss! I think that article needs to be amended to address this “bug” :)

I have never noticed before, I will leave a comment.

Last question - how do I do this tabular input for a Radio button? For example:

<?php echo CHtml::activeLabel($model, "[$i]default_item"); ?>

<?php echo CHtml::activeRadioButton($model, "[$i]default_item"); ?>

Each model has a label and a radio button; only one radio button can be selected from all the models.

EDIT: I resolved this as follows:

<?php echo CHtml::activeLabel($model, "[$i]default_item"); ?>

<?php echo CHtml::activeRadioButton($model, "default_item", array(


	'id'=>CHtml::activeId($model, "[$i]default_item"),


)); ?>