I want to dynamically add elements on a form using Ajax - this is the easy part. what I am having difficulty in doing is how best to deal with it using CFormModel. How do I create the model if I do not know the ammount of elements a user will add?
I want to dynamically add elements on a form using Ajax - this is the easy part. what I am having difficulty in doing is how best to deal with it using CFormModel. How do I create the model if I do not know the ammount of elements a user will add?
bump.
Anybody?
I haven’t done this myself, but I’d imagine you would add them as an array.
Assign the created fields names like Friend[] and it will return an array in $_POST with $_POST[‘Friend’][] ie ‘0’=>‘Mike’,‘1’=>‘Bob’, …
Well I have tried this (I think but cannot get it working)…
In my model…
public $questions = array();
In my view I have…
//..
<tr>
<td><?php echo CHtml::activeLabel($model,'questions[]'); ?></td>
<td><?php echo CHtml::activeTextField($model, 'questions[]', array('id' => 'questions_1')); ?></td>
</tr>
<tr>
<td><?php echo CHtml::activeLabel($model,'questions[]'); ?></td>
<td><?php echo CHtml::activeTextField($model, 'questions[]', array('id' => 'questions_2')); ?></td>
</tr>
I have hardcoded two text fields to test but when assigning the model->attributes it doesn’t recognise questions as an array…
Any other suggestions?
I just started myself, but I haven’t found a way to make Yii recognize an attribute as an array. Whenever I save anything to the database or work with the data, I always
implode(',',$_POST['Form']['questions']);
or the like…
I think I have this working…
In my model I declare the variable along with the others…
var $var1, $var2, $questions;
in my view it looks like this…
<table border="0" class="formtable">
<tr>
<td><?php echo CHtml::label('Question', 'questions[]'); ?></td>
<td><?php echo CHtml::textField('questions[]','',array('id' => 'questions_1')); ?></td>
</tr>
<tr>
<td><?php echo CHtml::label('Question', 'questions[]'); ?></td>
<td><?php echo CHtml::textField('questions[]','',array('id' => 'questions_2')); ?></td>
</tr>
and my controller is like this…
if(isset($_POST))
{
$model->attributes = $_POST;
if($model->validate())
{
print_r($model->questions);
}
}
Yii now recognises it as an array and I can still run validation rules. All I then have to do is adjust the tag id to a unique value e.g. question_1, question_2 etc.
Hope that helps somebody.