AjaxSubmmitButton[SOLVED]

Hola amigos soy nuevo en yii tengo 3 semanas y ahora me presento con un problema con ajax. Les platico tengo una vista en protected/views/theme/admin.php como lo siguiente


<?php

$this->breadcrumbs = array(

    'Manage Posts',

);

?>

<h1>Administracion Posts</h1>

<div class="form">

<?php echo CHtml::beginForm(); ?>




    <?php

    echo CHtml::ajaxSubmitButton(

            'Crear tema', array('ajax/Tema'), array(

        'update' => '#crearTema',

            )

    );

    ?>


<?php echo CHtml::endForm(); ?>

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


<div id="crearTema"></div>

<?php

// this is the date picker

$dateisOn = $this->widget('zii.widgets.jui.CJuiDatePicker', array(

            'model' => $model,

            'name' => 'Temas[date_first]',

            'language' => 'es',

            'value' => $model->date_first,

            'options' => array(

                'showAnim' => 'fold',

                'dateFormat' => 'yy-mm-dd',

                'changeMonth' => 'true',

                'changeYear' => 'true',

                'constrainInput' => 'false',

            ),

            'htmlOptions' => array(

                'style' => 'height:20px;width:80px;',

                'readonly' => "readonly",

            ),

                ), true) . '<br> a <br> ' . $this->widget('zii.widgets.jui.CJuiDatePicker', array(

            'name' => 'Temas[date_last]',

            'language' => 'es',

            'value' => $model->date_last,

            'options' => array(

                'showAnim' => 'fold',

                'dateFormat' => 'yy-mm-dd',

                'changeMonth' => 'true',

                'changeYear' => 'true',

                'constrainInput' => 'false',

            ),

            'htmlOptions' => array(

                'style' => 'height:20px;width:80px',

                'readonly' => "readonly",

            ),

                ), true);

?>

<?php

$this->widget('zii.widgets.grid.CGridView', array(

    'dataProvider' => $model->search(),

    'afterAjaxUpdate' => "function() {

                       jQuery('#Temas_date_first').datepicker(jQuery.extend({showMonthAfterYear:false}, jQuery.datepicker.regional['es'], {'showAnim':'fold','dateFormat':'yy-mm-dd','changeMonth':'true','showButtonPanel':'true','changeYear':'true','constrainInput':'false'}));

                       jQuery('#Temas_date_last').datepicker(jQuery.extend({showMonthAfterYear:false}, jQuery.datepicker.regional['es'], {'showAnim':'fold','dateFormat':'yy-mm-dd','changeMonth':'true','showButtonPanel':'true','changeYear':'true','constrainInput':'false'}));

                    }",

    'filter' => $model,

    'columns' => array(

        array(

            'name' => 'nombre',

        //'type'=>'raw',

        ),

        array(

            'name' => 'descripcion',

        ),

        array(

            'name' => 'fecha',

            'filter' => $dateisOn,

            'value' => '$data->fecha',

        ),

        array(

            'class' => 'CButtonColumn',

        ),

    ),

));

?>



Aquí se podran dar cuenta que hay un boton ajaxsubmit el cual me enviar a mi controlador que a su vez hace un render a otra vista. protected/controller/ajaxController




<?php


class AjaxController extends Controller {


    public function actionTema() {

        $model = new Temas();

        $this->renderPartial('/theme/_formAjax', array('model' => $model));

        // $this->renderPartial('/theme/_form', array('model' => $model));

        Yii::app()->end();

    }


    public function actionCrear() {

        $model = new Temas;


        if (isset($_POST['Temas'])) {

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

// $model->attributes =Yii::app()->user->getId();

            if ($model->validate()) {


                $nombre = '=?UTF-8?B?' . base64_encode($model->nombre) . '?=';

                $descripcion = '=?UTF-8?B?' . base64_encode($model->descripcion) . '?=';

                $fecha = '=?UTF-8?B?' . base64_encode($model->fecha) . '?=';

                $usuarios_id = '=?UTF-8?B?' . base64_encode($model->usuarios_id) . '?=';

                if($model->save()){

                 //   exit(json_encode(array('result'=>'success','msg'=>'Registro exitoso')));

                     $this->renderPartial('/theme/admin', array('model' => $model),false,true);

                }else{

                    exit(json_encode(array('result'=>'error','msg'=>CHtml::errorSummary($model))));

                }

            }

        }

        $this->renderPartial('/theme/admin', array('model' => $model),false,true);

         //exit(json_encode(array('result'=>'error','msg'=>'No input data has been passed.')));

    }


}




y finalmente mi formulario vista, donde el usuario tiene que llenar algunos campos y poder hacer un registro, el boton del registro tambien es un ajaxsubmit el cual si cumple con las caracteristica lo guarda en la BD, de lo contrario manda los errores, de la manera que lo hice guarda y manda los errores pero el botton no me funciona como ajax ya que me redericciona a otra vista y no se queda donde deberia.

/protected/views/theme/_formAjax.php




<div class="form">

    <?php

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

        'id'=>'user-form',

        'enableAjaxValidation'=>true,

        'action'=>$this->createUrl('ajax/Crear'),

        'enableClientValidation'=>true,)

            );

    ?>




    <p class="note">Campos con <span class="required">*</span> son requeridos.</p>


    <?php echo CHtml::errorSummary($model); ?>


    <div class="row">

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

        <?php echo $form->textField($model, 'nombre', array('size' => 80, 'maxlength' => 128)); ?>

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

    </div>


    <div class="row">

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

        <?php echo CHtml::activeTextArea($model, 'descripcion', array('rows' => 10, 'cols' => 70)); ?>

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

    </div>


    <div class="row">

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

        <?php echo $form->textField($model, 'fecha', array('size' => 80, 'maxlength' => 128)); ?>

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

    </div>

    <div class="row">


        <?php $model->usuarios_id = Yii::app()->user->getId(); ?>

        <?php echo $form->hiddenField($model, 'usuarios_id', array('readonly' => true)); ?>

    </div>




    <div class="row buttons">

        <?php

        echo CHtml::ajaxSubmitButton('Guardar',CHtml::normalizeUrl(array('ajax/','render'=>true)),

                 array(

                     'dataType'=>'json',

                     'type'=>'post',

                     'success'=>'js:function(data) {

                        if(data.status=="success"){

                         $("#formResult").html("form submitted successfully.");

                         $("#user-form")[0].reset();

                        }

                         else{

                        $.each(data, function(key, val) {

                        $("#user-form #"+key+"_em_").text(val);                                                    

                        $("#user-form #"+key+"_em_").show();

                        });

                        }       

                    }',                    

                     

                     ),array('id'=>'mybtn','class'=>'class1 class2'));

        ?>

    </div>

   

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

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

De antemano muchas gracias y disculpen las molestias.

Buenas.

Yo quitaría esto:




Yii::app()->end();



De la acción Tema y probaría.

Muchas gracias lagogz, el problema era mi id del button, ya que esta tratando de tener dos botones ajaxsubmit en una misma vista, y estos cuando trataban de comunicarse con mi controlador aunque eran distintas acciones, yii de alguna manera le daba la misma accion a los dos por tener el mismo id, entonces solo cambie el id


array('id' => uniqid()

y ya cada boton se iba a su propia accion de esta manera ya funciona perfecto.

gracias por tu respuesta.

Efectivamente, si utilizas botonones ajax en Yii es conveniente darles su propio id y nombre.

Un saludo.