AJAX Form Manipulation

What I’m trying to do is take a form that is asking users to specify details of a file they want to save to a database and use an AJAX link to swap out a file upload field for a text box to enter a direct link url instead.

I’m using a CRUD interface for the form and have this in my _form.php


<div class="row">

        <div id="ajaxDLLink">

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

            <?php echo $form->fileField($model, 'downloadFile');  ?>

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

            <?php echo CHtml::ajaxLink('Enter a URL instead?', array('ajaxLink'), array('update'=>'#ajaxDLLink')); ?>

        </div>


    </div>

My controller has this code


public function actionAjaxLink()

    {

       $this->renderPartial('_directLink', array(), false, true);

    }

And _directLink.php has this code


<?php

    echo $form->labelEx($model,'downloadLink');

    echo $form->textField($model,'downloadLink',array('size'=>60));

    echo $form->error($model,'downloadLink');

?>



This is generating errors in _directLink.php about $form not being defined. $form is defined in the top of _form.php as


<?php $form=$this->beginWidget('CActiveForm', array(

	'id'=>'files-form',

	'enableAjaxValidation'=>false,

    'htmlOptions'=>array('enctype'=>'multipart/form-data'),

)); ?>

Am I going about this the wrong way? I’d like some advice if so about what I should do instead.

Many thanks

You don’t need AJAX for field type changing :)

OK… care to elaborate?

Additionally, assuming that I wanted to do something similar but more elaborate. Is it possible to swap one form field for say 4 form fields at the click of a button.

Also I want to add a form field with a button to add extra of the same type. So for example

<input name="upload[]" id="upload" type="file" />

With a button that would add the same html again and again every time the button is pressed. The result would then be passed back as an array.

Really would appreciate any help here or pointers to good tutorials. Very new to Yii and the correct way of handling things.

Ok, I’ll try to elaborate:

you can use plain old DHTML to show/hide form elements, for example:




<div id="fieldset1" style="display:none">

    <input type="file" name="f1">

</div

<div id="fieldset2">

    <input type="text" name="f2">

    <input type="text" name="f3">

</div>

<a href="#" onclick="$('#fieldset1').toggle();$('#fieldset2').toggle();return false;">test</a>



Speaking about extra fields, have a look at Jquery Dynamic Forms, I think this is what you need.

Thanks for the reply. I’ll take a look into it :)