Form with AJAX

Help me, please!

I need to put some fields into a form using Ajax.

For each contact I add a field.

After add all textfields and submit the form, I can`t retrieve the new values from the fields inserted via AJAX.

How can I get or submit this values?

To solve this issues what I do is to create a function that will handle all elements in the form. You could include that function through a .live, or a onsubmit, or whatever…

The function needs to get the elements of the form by serializing this latest. For example:

onclick="javascript: var data = $(this.form).serialize(); $.ajax(…"

Hope it helps

Where I do it?

Here is the code:

The User _form (will receive the fields):




<div class="form">


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

	'id'=>'pagamarela-form',

	'enableAjaxValidation'=>false,

)); ?>


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


        <div class="row">

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

		<?php echo $form->textField($model,'nome',array('size'=>60,'maxlength'=>150)); ?>

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

	</div>


	<div class="row">

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

            <?php echo CHtml::activeDropDownList($model, 'id_categoria', $model->getListaCategorias(), array('prompt'=>$funcao)); ?>

            <?php echo CHtml::ajaxLink(Yii::t('categoria','Criar Categoria'),$this->createUrl('categoria/criarCategoria'),array(

                'onclick'=>'$("#categoriaDialog").dialog("open"); return false;',

                'update'=>'#categoriaDialog'

                ),array('id'=>'showCategoriaDialog'));

            ?>

            <div id="categoriaDialog"></div>

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

	</div>


	<div class="row">

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

            <?php echo CHtml::activeDropDownList($model, 'id_funcao', $model->getListaFuncoes(), array('prompt'=>$funcao)); ?>

            <?php echo CHtml::ajaxLink(Yii::t('funcao','Criar Fun&ccedil;&atilde;o'),$this->createUrl('funcao/criarFuncao'),array(

                'onclick'=>'$("#funcaoDialog").dialog("open"); return false;',

                'update'=>'#funcaoDialog'

                ),array('id'=>'showFuncaoDialog'));

            ?>

            <div id="funcaoDialog"></div>

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

	</div>


	<div class="row">

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

            <?php echo CHtml::activeDropDownList($model, 'id_empresa', $model->getListaEmpresas(), array('prompt'=>$funcao)); ?>

            <?php echo CHtml::ajaxLink(Yii::t('empresa','Criar Empresa'),$this->createUrl('empresa/criarempresa'),array(

            'onclick'=>'$("#empresaDialog").dialog("open"); return false;',

            'update'=>'#empresaDialog'

            ),array('id'=>'showEmpresaDialog'));

            ?>

            <div id="empresaDialog"></div>

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

	</div>


        <div class="row">

            <label>Meios de contato:</label>            

        </div>


        <div class = "row" id="cel">            

        </div>

        <div id="celular">

            <?php echo CHtml::ajaxLink('Inserir Celular',$this->createUrl('meios/criarmeio',array('dispositivo'=>'celular')),array(

            'onclick'=>'$("#meiosDialog").dialog("open"); return false;',

            'update'=>'#meiosDialog'

            ),array('id'=>'showMeiosDialog'));

            ?>

        </div>

        <div id="meiosDialog"></div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row">

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

		<?php echo $form->textArea($model,'observacao',array('rows'=>6, 'cols'=>50)); ?>

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

	</div>


	<div class="row">

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

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

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

	</div>


	<div class="row buttons">

		<?php echo CHtml::submitButton($model->isNewRecord ? 'Salvar' : 'Salvar'); ?>

	</div>


<?php $this->endWidget(); ?>


</div><!-- form -->



the user controller:




        public function actionCreate()

	{

		$model=new Pagamarela;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


		if(isset($_POST['Pagamarela']))

		{

			$model->attributes=$_POST['Pagamarela'];

                        $arrayMeios = $_POST['Pagamarela']['meios'];

                        $status = $_POST['Pagamarela']['status'];

                        Yii::log($arrayMeios,'info','arraymeios');

                        Yii::log($status,'info','status');


                        if(!empty($arrayMeios)){

                            foreach($arrayMeios as $meio){

                                Yii::log($meio,'info','meio');

                            }

                        }

			if($model->save())

				$this->redirect(array('index'));

		}


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

			'model'=>$model,

		));

	}



the ajax form (will write the fields):




<?php

    $this->beginWidget('zii.widgets.jui.CJuiDialog',array(

        'id'=>'createDialog',

        'options'=>array(

            'title'=>Yii::t('meios','Criar Meio de contato'),

            'autoOpen'=>'true',

            'modal'=>'true',

            'width'=>'auto',

            'height'=>'auto',

        ),

        ));

    echo $this->renderPartial('_formDialog', array('model'=>$model));

    $this->endWidget('zii.widgets.jui.CJuiDialog');

?>



and cel controller




public function actionCriarMeio(){

            $model = new Meios;

            // Uncomment the following line if AJAX validation is needed

            $this->performAjaxValidation($model);


            // copiado do exemplo no site: http://www.yiiframework.com/wiki/72/cjuidialog-and-ajaxsubmitbutton

            // Flag to know if we will render the form or try to add

            // new jon.

            $flag=true;


            if(isset($_POST['Meios']))

            {

                $flag=false;

                $model->attributes=$_POST['Meios'];

                if($model->save()){

                    $name = $model->id;

                    $value = $model->valor;

                    $htmlOptions = array('readonly'=>'readonly');

                    //Return an <option> and select it

                    //echo CHtml::tag('option', array('value'=>$model->id,'selected'=>true),CHtml::encode($model->nome),true);

                    echo "<div id='row'>";

                    echo CHtml::label($name, $name);

                    echo CHtml::textField($name, $value, $htmlOptions);

                    echo CHtml::hiddenField("Pagamarela_meios[$name]", $name);

                    echo CHtml::hiddenField("Pagamarela_status", $name);

                    echo "</div>";                    

                }

            }

            if ($flag)

                    $this->renderPartial('createDialog',array('model'=>$model,),false,true);

        }



and the form to render (_formDialog):




<div class="form" id="formMeios">

<?php $form=$this->beginWidget('CActiveForm', array('id'=>'meios-form', 'enableAjaxValidation'=>false,)); ?>

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


    <div class="row">

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

            <?php echo $form->textField($model,'dispositivo',array('size'=>60,'maxlength'=>100)); ?>

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

    </div>

    <div class="row">

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

            <?php echo $form->textField($model,'tipo',array('size'=>60,'maxlength'=>100)); ?>

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

    </div>

    <div class="row">

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

            <?php echo $form->textField($model,'valor',array('size'=>60,'maxlength'=>100)); ?>

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

    </div>


    <div class="row buttons">

        <?php echo CHtml::ajaxSubmitButton('Criar Meio de contato',CHtml::normalizeUrl(array('meios/criarmeio','dispositivo'=>'cel', 'render'=>false)),

            array('success'=>'js:function(data){$("#cel").append(data);$("#formMeios").reset();$("#meios-form").dialog("close");}'),array('id'=>'closeMeiosDialog'));

        ?>

    </div>

<?php $this->endWidget(); ?>

</div><!-- form -->



Any idea?

Forget what I said, your approach is completely different from what I thought.

I think your problem is this:

echo CHtml::hiddenField("Pagamarela_meios[$name]", $name);

echo CHtml::hiddenField("Pagamarela_status", $name);

if Pagamarela is your model and meios is your attribute then:

echo CHtml::hiddenField("Pagamarela[meios][$name]",$name);

echo CHtml::hiddenField("Pagamarela[status]",$name);

Is the correct approach to:

$model->attributes=$_POST[‘Pagamarela’];

$arrayMeios = $_POST[‘Pagamarela’][‘meios’];

$status = $_POST[‘Pagamarela’][‘status’];