D
D
Doniyor Mamatkulov2015-10-09 14:14:58
JavaScript
Doniyor Mamatkulov, 2015-10-09 14:14:58

Dynamically adding Yii elements to a form using jQuery?

I'm having a problem integrating Yii and jQuery when I'm trying to dynamically add elements to a form. So, statically, the select field is added like this:

echo $form->label($model,Yii::t('candidates', 'Contact type'));
$options = CHtml::listData(HrpContactTypes::model()->findAll(),'id','type');
 $ct = array();
 $b=1;
for($i=0;$i<=count($options)-1;$i++) {
    $ct[$b] = Yii::t('candidates', $options[$b]);
    $b++;
}
echo $form->dropDownList($model,'contact_type_id',$ct,array('class'=>'form-control'));

and so I add an input:
echo $form->label($model,Yii::t('candidates', 'Contact')); ?>
echo $form->textField($model,'contact', array('required'=>'required', 'class'=>'form-control' ));

This is how my code for dynamically adding elements to the form looks like:
$('#addContact').click(function() {
        $('#row').append(
            '<br><div class="col-md-6">contact type</div><div class="col-md-6">contact</div>'
            );
        return false;
    });

And accordingly my question is: how to dynamically add Yii elements to the form?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya Levin, 2015-10-19
@ilyachase

Yii2 has a js library for ActiveForm. According to this guide, you can do this:

$('#contact-form').yiiActiveForm('add', {
    'id': 'contact',
    'name': 'contact',
    'container': '.field-contact',
    'input': '#contact',
    'error': '.field-contact .help-block'
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question