Yii Framework Forum: [Solved]Validation Error With Ajax Submit - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

[Solved]Validation Error With Ajax Submit [SOLVED] Rate Topic: -----

#1 User is offline   lagogz 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 334
  • Joined: 30-November 12
  • Location:Galiza

Posted 28 January 2013 - 11:18 AM

Good afternoon.

When I submit a form using AJAX, model validation rules are not shown. They work but the page does not refresh properly. I know it works because if I check console/html in firebug shows me the notice required field, but does not load the page.

I have:

views/toMedicamentos/_form.php

<script>
    $("body").on("click","#submitMedicamento",function(){
        var data={};
        var selected = $("#to-pactivos-grid").selGridView("getAllSelection");
        
        data.valorMedicamento = $('#ToMedicamentos_Medicamento').val();
 
        if (!selected.length)
        {
            alert('Please select minimum one item to be deleted');
            return false;
        }
        else
            data.selectedItems=selected;
 
        $.ajax({
                type: "POST",
                url: "index.php?r=toMedicamentos/create",
                data: data,
                success: (function (data){
                    var redireccionar = data['redireccionar'];
                    window.location.href = redireccionar;
                }),
                error: function(data) { // if error occured
                    alert("Error occured.please try again");
                    alert(data);
               },
               dataType:'json'
            });
 
        return false;
    });
....
....
<?php $form=$this->beginWidget('CActiveForm', array(
            'id'=>'to-medicamentos-form',
            'enableAjaxValidation'=>true,
        )); ?>
 
        <div class="solid_border">
            </br>
 
            <?php echo $form->errorSummary($modelMedicamentos); ?>
 
            <div class="row">
                <?php echo $form->labelEx($modelMedicamentos,'Medicamento'); ?>
                <?php echo $form->textField($modelMedicamentos,'Medicamento',array
                ('size'=>60)); ?>
                <?php echo $form->error($modelMedicamentos,'Medicamento'); ?>
            </div>
        </div>

        <?php
            $headerPActivos;

            If(!$modelMedicamentos->isNewRecord){
               $headerPActivos='Principios Activos Relacionados';
            }
            else{
                $headerPActivos='Principios Activos';
            }

            $this->widget('application.components.SelGridViewGal', array(
                'id'=>'to-pactivos-grid',
                'dataProvider'=>$modelPActivos->searchMedicamentosPActivos($IdMedicamento),
                'filter'=>$modelPActivos,
                'selectableRows' => 2,
                'columns'=>array(
                                array(
                                    'class' => 'CCheckBoxColumn'
                                    ),
                                array(
                                    'header'=>$headerPActivos,
                                    'name'=>'Principio_Activo',
                                    'value'=>'$data->Principio_Activo'),
                                array(
                                        'class'=>'CButtonColumn',
                                        'template'=>'{view}{update}',//{delete}',
                                        'viewButtonUrl' => 'array("ToPrincipiosActivos/view",
                                        "id"=>$data->IdPrincipio_Activo)',
                                        'viewButtonLabel'=>'Ver Detalle',
                                        'updateButtonUrl' => 'array("ToPrincipiosActivos/update",
                                        "id"=>$data->IdPrincipio_Activo)',
                                        'updateButtonLabel'=>'Actualizar',
                                    ),
                            ),
            )); 

            echo CHtml::button(
                            $modelMedicamentos->isNewRecord ? 'Alta' : 'Actualizar',
                            array('id'=>'submitMedicamento')
                            );
            ?>
        </div>
....
....


ToMedicamentos/actionCreate

public function actionCreate()
    {
        $transaction=Yii::app()->db->beginTransaction();

        try
        {
            $modelMedicamentos=new ToMedicamentos;
            $IdMedicamento=0;
            $modelPActivos=new ToPrincipiosActivos; 

            $modelMPA = new TvPactivosMedicamentos("searchIncludingPActivos($IdMedicamento)");
            $modelMPA->unsetAttributes();
            $modelMPA->scenario = 'searchIncludingPActivos';

            if(isset($_POST['valorMedicamento']))
            {   
                $modelMedicamentos->unsetAttributes();
                $modelMedicamentos->Medicamento=$_POST['valorMedicamento'];

                if($modelMedicamentos->save())/* Save the Role model */
                {
                    $IdMedicamento = $modelMedicamentos->IdMedicamento;

                    foreach ($_POST['selectedItems'] as $IdPrincipio_Activo) {
                        $this->linkChildRecord($IdMedicamento, $IdPrincipio_Activo);
                    }
                    
                    $transaction->commit();
                
                    $response=array();
                    $response['redireccionar']='index.php?r=ToMedicamentos/view&id='.$IdMedicamento;
                    
                    echo CJSON::encode($response);
                    Yii::app()->end();
                }
            }

            $this->render('create',array(
                                        'modelMedicamentos'=>$modelMedicamentos,
                                        'modelMPA'=>$modelMPA,
                                        'modelPActivos'=>$modelPActivos,
                                        'IdMedicamento' => $IdMedicamento,
            ));            
        }
        catch(Exception $e)
        {
           $transaction->rollback();
        }
    }


model ToMedicamentos, rules

public function rules()
    {
        return array(
                    array('Medicamento', 'required'),
                    array('Medicamento', 'unique'),
                    array('Medicamento', 'safe', 'on'=>'search'),
        );
    }


I tried to write this in actionCreate, but redirects losing validation:

if(Yii::app()->request->getIsAjaxRequest())
            {
                $response=array();
                $response['redireccionar']='index.php?r=ToMedicamentos/create';

                echo CJSON::encode($response);
            }
            else
            {
                $this->render('create',array(
                                            'modelMedicamentos'=>$modelMedicamentos,
                                            'modelMPA'=>$modelMPA,
                                            'modelPActivos'=>$modelPActivos,
                                            'IdMedicamento' => $IdMedicamento,
                ));      
            }


Regerds.
-----------------------------------------------------------------------------------------------
------------------------------- VISITEN FOCUCHASART --------------------------------
-----------------------------------------------------------------------------------------------
0

#2 User is offline   lagogz 

  • Advanced Member
  • PipPipPip
  • Yii
  • Group: Members
  • Posts: 334
  • Joined: 30-November 12
  • Location:Galiza

Posted 05 February 2013 - 09:24 AM

Good afternoon all!

I revolved my problem by removing AJAX submit and sending data by PHP submit.

I modified the AJAX functions for appearance and ready.

Regards.
-----------------------------------------------------------------------------------------------
------------------------------- VISITEN FOCUCHASART --------------------------------
-----------------------------------------------------------------------------------------------
0

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users