Mensaje De Alerta

Hola comunidad, ante todo mis saludos y agradecimiento por las ayudas que me puedan brindar.

El problema es que tengo en mi sistema dos tablas para guardar las prefacturas, en una (prefacturas) se guardan los datos generales con los campos: nprefac, fecha, Codsalida, CodCliente, CodUEB, CodMon, CI, CodPVen en esta tabla [size="2"]nprefac es la clave principal, la misma es varchar(10).[/size]

[size="2"]En otra tabla ([/size]detallespre[size="2"]) tengo los detalles de la prefactura con los campos: Id, [/size]Id_pre, Codprod, cantidad, Codpre, Cosdes, Codrec, estas dos tablas esta relacionadas uno a muchos por los campos [size="2"]nprefac de [/size][size="2"]prefacturas con [/size][size="2"]Id_pre de [/size]detallespre[size="2"] en la tabla[/size] prefacturas [size="2"]no puede haber articulos repetidos, ya que es llave principal, por lo que es el objeto de este tema, quiero que cuando intente crear un numero de factura que ya exista en la tabla [/size][size="2"]prefacturas, me envie un mensaje que el numero ya existe y no se puede crear.[/size]

Para crearla hice en mi controlador esta función, como verán ella me crea el articulo, pero no me da el mensaje de alerta que quiero lo que hace es no crearla y el navegador se queda parado, si la veo por herramientas de desarrollo me da el error que no se puede crear ya que se crearía repetido y los usuarios finales no saben verla por aquí, entonces necesito me de la alerta:

alcgo asi:




 else

              alert("No puede crearla ya que existe ese número");



Esta es la función de mi controlador




public function actionSalvarPrefac() {

        $id=$_POST['modelid'];

   	

		if($id)

                $model=$this->loadModel($id);   

        else            

                

				$model = new Prefacturas;   

        

        if(isset($_POST['detalle'])) {//se guarda en la tabla prefacturas

        //Lo que se guarda en tabla Prefacturas

              $model->fecha=$_POST['fecha'];

              $model->nprefac=$_POST['nprefac'];

              $model->Codsalida=$_POST['codsalida'];

              $model->CodCliente=$_POST['cliente'];

              $model->CodUEB=$_POST['codueb'];

              $model->CodMon=$_POST['codmon'];

              $model->CI=$_POST['ci'];

              $model->CodPVen=$_POST['codpven'];

         

   	if ($model->save()) {

                Detallespre::model()->deleteAll('Id_pre=:nprefac', array(':nprefac'=>$model->nprefac));


        foreach($_POST['detalle'] as $item){

            //Lo que se guarda en tabla Detallespre

            $detalle=new Detallespre;      

            $detalle->Id_pre=$model->nprefac;

            $detalle->Codprod=$item['producto'];

            $detalle->cantidad=$item['cantidad'];

            $detalle->Codpre=$item['precio'];

            $detalle->Cosdes=$item['descuento'];

            $detalle->Codrec=$item['recargo'];

            $detalle->save();

               	}

              }

     	}

    }



Necesito me ayuden con el mensaje de alerta:

amigo porque no defines en las reglas de validacion el campo como "unique" Rules Unique en tu modelo de esa forma con esa regla no podrán repetir dicho numero en el campo, si quieres poner un mensaje personalizado cuando se genera el error aqui te dejo para que veas el ejemplo --> Personalizar mensaje de error … en tal caso de que desees mostrar un alert seria de la siguiente forma --> flash yii

Espero querido amigo que los enlaces que te envió te ayuden con tu problema de igual manera en caso de que continúes con la duda la pones aquí para

Hola amigo erickMartinez, en mi modelo ya tengo esa regla aplicada.





public function rules()

	{

		// NOTE: you should only define rules for those attributes that

		// will receive user inputs.

		return array(

			array('nprefac', 'required'),

            array('Codsalida, CodMon', 'numerical', 'integerOnly'=>true),

			array('nprefac', 'length', 'max'=>10),

			array('CodCliente, CodUEB, CodPVen', 'length', 'max'=>12),

			array('CI', 'length', 'max'=>11),

			array('fecha', 'safe'),

			// The following rule is used by search().

			// Please remove those attributes that should not be searched.

			array('nprefac, fecha, Codsalida, CodCliente, CodUEB, CodMon, CI, CodPVen', 'safe', 'on'=>'search'),

		);

	}



Como veras ya tengo esa regla y realmente no me permite duplicar un muero, lo que quiero es que me envíe un mensaje de alerta

creo que en este post que encontré hacen lo que tu quieres … mostrar los errores en ventanas de alerta :D

http://www.yiiframework.com/forum/index.php/topic/42577-message-alert-from-controller/

y aqui otro :D

http://www.yiiframework.com/forum/index.php/topic/48506-how-to-create-yii-popup-message-box/

Hola a todos de nuevo, ya tengo hecho en otros momento algo de mensaje de alerta, el problema es que aquí en especifico no se como hacerlo, por ejemplo para comprobar saldos tengo lo siguiente:

en el controlador





public function actionComprobarSaldo()

{

        $codigo=$_POST['codigo'];

	$cantidad=$_POST['cantidad'];

	$codigoPVen=$_POST['codigoPVen'];			

	$criteria=new CDbCriteria;                                        

	$criteria->addCondition('CodPVen=:codpto'); 

	$criteria->addCondition('Codprod=:codigo'); 	

	$criteria->params=array(':codpto'=>$codigoPVen , ':codigo'=>$codigo);		

	$objSubmp = Submayorprod::model()->find($criteria);

	

	if($objSubmp->SaldoAct < $cantidad)

		echo "error";

	else

		echo "ok";	

			

}



y en la vista





$.ajax({

			url: 'index.php?r=datossal/comprobarSaldo',

			type: 'POST',

			dataType: 'text',

			data: {	"codigo":codigo, 

                                "codigoPVen":codigoPVen,

                                "cantidad": cantidad,

                                "precio": precio,

                                "descuento": descuento,

                                "recargo": recargo

					},

			success: function(data) {

					

                            if(data.trim()=="ok")

                            {

                                    $("#tblData tbody").append(

                                    "<tr class='even'>"+    

                                    "<td>"+ codigo +"</td>"+

                                    "<td>"+ $('#producto option:selected').text()+"</td>"+

                                    "<td>"+ cantidad +"</td>"+   

                                    "<td>"+ precio +"</td>"+ 

                                    "<td>"+ descuento +"</td>"+ 

                                    "<td>"+ recargo +"</td>"+ 

                                    "<td><img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'>    <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/></td>"+

                                    "</tr>");

                                    

                                    $(".btnEdit").off("click");

                                    $(".btnDelete").off("click");

                                    $(".btnEdit").on("click", Edit);     

                                    $(".btnDelete").on("click", Delete);

                                        

                                    document.getElementById('incantidad').value ='';

                                    document.getElementById('inprecio').value =''; 

                                    document.getElementById('indescuento').value =''; 

                                    document.getElementById('inrecargo').value =''; 

                                    $('#producto option:selected').remove();


                                    ActualizarCodigo();

                            }

                            else

                                    alert("No tiene saldo para facturar");

			}

		});



Como ven ya tengo hecho eso en otros casos, pero aquí en este caso no se como hacerlo

Por ejemplo talvez podria poner algo así en el controlador





public function actionComprobarNFactura()

{

        $numero=$_POST['nprefac'];	

	$criteria=new CDbCriteria;                                        

	$criteria->addCondition('nprefac=:nprefac'); 

	

	$criteria->params=array(':nprefac'=>$numero);		

	$objNprefac = Prefacturas::model()->find($criteria);

	

	if($objNprefac->nprefac = $numero)

           

		echo "error";

	else

		echo "ok";	

			

}



pero en la forma como lo haría, esta es mi forma completa:





<?php

/* @var $this PrefacturasController */

/* @var $model Prefacturas */

/* @var $form CActiveForm */

?>

<script>


$(function(){

    //Add, Save, Edit and Delete functions code

    $(".btnEdit").on("click", Edit);

    $(".btnDelete").on("click", Delete);

    $("#btnAdd").on("click", Add);	

    ActualizarCodigo();

	

	$.ajax({

		url: 'index.php?r=prefacturas/actualizarFirmantes',      

        type: 'POST',

        dataType:'json',

        data: {

				"idCodigo": $('#Prefacturas_CodCliente').val()

            	},

        success: function(data) {

				$("#Prefacturas_CI").html(data.firmantes); 

        }

    });

	

});


function Add(){


	if($('#producto option:selected').text()!=''){

	

	var codigo= $('#incodigo').val()==''?'0':$('#incodigo').val();

        var cantidad= $('#incantidad').val()==''?'0':$('#incantidad').val();

        var precio= $('#inprecio').val()==''?'0':$('#inprecio').val();

        var descuento= $('#indescuento').val()==''?'0':$('#indescuento').val();

        var recargo= $('#inrecargo').val()==''?'0':$('#inrecargo').val();

       

		var codigoPVen= $('#Prefacturas_CodPVen').val(); 

	

		$.ajax({

			url: 'index.php?r=prefacturas/comprobarSaldo',

			type: 'POST',

			dataType: 'text',

			data: {	"codigo":codigo, 

                                "codigoPVen":codigoPVen,

                                "cantidad": cantidad,

                                "precio": precio,

                                "descuento": descuento,

                                "recargo": recargo

					},

			success: function(data) {

					

                            if(data.trim()=="ok")

                            {

                                    $("#tblData tbody").append(

                                    "<tr class='even'>"+    

                                    "<td>"+ codigo +"</td>"+

                                    "<td>"+ $('#producto option:selected').text()+"</td>"+

                                    "<td>"+ cantidad +"</td>"+   

                                    "<td>"+ precio +"</td>"+ 

                                    "<td>"+ descuento +"</td>"+ 

                                    "<td>"+ recargo +"</td>"+ 

                                    "<td><img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'>    <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/></td>"+

                                    "</tr>");

                                    

                                    $(".btnEdit").off("click");

                                    $(".btnDelete").off("click");

                                    $(".btnEdit").on("click", Edit);     

                                    $(".btnDelete").on("click", Delete);

                                        

                                    document.getElementById('incantidad').value ='';

                                    document.getElementById('inprecio').value =''; 

                                    document.getElementById('indescuento').value =''; 

                                    document.getElementById('inrecargo').value =''; 

                                    $('#producto option:selected').remove();


                                    ActualizarCodigo();

                            }

                            else

                                // alert("Error: " + data.error);                                   

                                alert("No tiene saldo para reservar");

			}

		});			       

	}

	else{

		alert('No quedan productos para adicionar');

	}

		

};


var oldCantidad;

var oldCodpr;

var oldCosdes;

var oldCodrec;

function Edit(){

    var par = $(this).parent().parent(); //tr

    var tdCantidad = par.children("td:nth-child(3)");  

    var tdCodpre = par.children("td:nth-child(4)"); 

    var tdCosdes = par.children("td:nth-child(5)"); 

    var tdCodrec = par.children("td:nth-child(6)"); 

    var tdButtons = par.children("td:nth-child(7)");

    

    oldCantidad=tdCantidad.html();

    oldCodpre=tdCodpre.html();

    oldCosdes=tdCosdes.html();

    oldCodrec=tdCodrec.html();

    

   tdCantidad.html("<input type='text' id='txtCantidad' value='"+tdCantidad.html()+"'/>"); 

   tdCodpre.html("<input type='text' id='txtCodpre' value='"+tdCodpre.html()+"'/>"); 

   tdCosdes.html("<input type='text' id='txtCosdes' value='"+tdCosdes.html()+"'/>"); 

   tdCodrec.html("<input type='text' id='txtCodrec' value='"+tdCodrec.html()+"'/>"); 

   tdButtons.html("<img src='images/save.png' class='btnSave' title='Guardar' style='cursor:pointer'/>    <img src='images/cancel.gif' class='btnCancel' title='Cancelar' style='cursor:pointer'/>");

 

    $(".btnEdit").off("click");

    $(".btnDelete").off("click");

    $(".btnSave").on("click", Save);

    $(".btnCancel").on("click", Cancel);

    $(".btnEdit").on("click", Edit);

    $(".btnDelete").on("click", Delete);

};


function Save(){

    var par = $(this).parent().parent(); //tr

    var tdCantidad = par.children("td:nth-child(3)"); 

    var tdCodpre = par.children("td:nth-child(4)"); 

    var tdCosdes = par.children("td:nth-child(5)"); 

    var tdCodrec = par.children("td:nth-child(6)"); 

    var tdButtons = par.children("td:nth-child(7)");

   

     

    tdCantidad.html(tdCantidad.children("input[type=text]").val());  

    tdCodpre.html(tdCodpre.children("input[type=text]").val());  

    tdCosdes.html(tdCosdes.children("input[type=text]").val());  

    tdCodrec.html(tdCodrec.children("input[type=text]").val());  

    tdButtons.html("<img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'/>    <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/>");

 

    $(".btnEdit").off("click");

    $(".btnDelete").off("click");

    $(".btnEdit").on("click", Edit);

    $(".btnDelete").on("click", Delete);

};


function Cancel(){

    var par = $(this).parent().parent(); //tr

    var tdCantidad = par.children("td:nth-child(3)"); 

    var tdCodpre = par.children("td:nth-child(4)"); 

    var tdCosdes = par.children("td:nth-child(5)"); 

    var tdCodrec = par.children("td:nth-child(6)"); 

    var tdButtons = par.children("td:nth-child(7)");

        

    tdCantidad.html(oldCantidad); 

    tdCodpre.html(oldCodpre);

    tdCosdes.html(oldCosdes);

    tdCodrec.html(oldCodrec);

    tdButtons.html("<img src='images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'/>    <img src='images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/>");

 

    $(".btnEdit").off("click");

    $(".btnDelete").off("click");

    $(".btnEdit").on("click", Edit);

    $(".btnDelete").on("click", Delete);

};




function Delete(){

    var par = $(this).parent().parent(); //tr

	$('#producto')

         .append($("<option></option>")

         .attr("value",par.children("td:nth-child(1)").html())

         .text(par.children("td:nth-child(2)").html())); 

 

         ActualizarCodigo();

	

    par.remove();

};


function ActualizarCodigo(){

    

    $('#incodigo').val($('#producto option:selected').val());


};


$('#prefacturas-form').live('submit',function(event) {


	var tbl = $('#tblData tbody tr').map(function() {

                var row = $(this);

                return {	producto: row.find(':nth-child(1)').text(),

                cantidad: row.find(':nth-child(3)').text(),

                precio: row.find(':nth-child(4)').text(),

                descuento: row.find(':nth-child(5)').text(),

                recargo: row.find(':nth-child(6)').text(),

                        };

                }).get();

	

    $.ajax({

        url: 'index.php?r=prefacturas/salvarPrefac',

        type: 'POST',

        dataType: 'text',

        data: {"detalle":tbl, 

		"fecha": $('#Prefacturas_fecha').val(),

		"nprefac":$('#Prefacturas_nprefac').val(),

		"codsalida":$('#Prefacturas_Codsalida').val(),

		"cliente":$('#Prefacturas_CodCliente').val(),

		"codueb":$('#Prefacturas_CodUEB').val(),

                "codpven":$('#Prefacturas_CodPVen').val(),

		"codmon":$('#Prefacturas_CodMon').val(),

		"ci":$('#Prefacturas_CI').val(),

                 "modelid":$('#modelid').val() 

            	},

        success: function(data) {

		window.location.href='index.php?r=prefacturas/admin';	

        }

    });

    return false;

});

</script>


<style>

.mystyle

{

	background: white;

	border-collapse: collapse;

	width: 100%;

	border: 1px #D0E3EF solid;

	

}

.mystyle th, .mystyle td

{	

	border: 1px white solid;

	padding: 0.3em;

}

.mystyle th

{

	color: white;

	background: #69A8CD;

	text-align: center;

}

.mystyle tr.even

{

	background: #F8F8F8;

}

.mystyle tr.odd

{

	background: #E5F1F4;

}

.mystyle tr.selected

{

	background: #BCE774;

}

.mystyle tbody tr:hover

{

	background: #ECFBD4;

}


</style>

<div class="form">

<table width="217" border="1">

  <tr>

    <td width="45"><div align="left">

      <?php        

        echo CHtml::submitButton('Existencias por entidades', array('submit'=>array('/reportes/Existencias'))); 

    ?>

    </div></td>

    <td width="25"><div align="left">

      <?php        

        echo CHtml::submitButton('Estado del cliente', array('submit'=>array('/reportes/Clientes')));

	    ?>

	 <td width="61"><div align="left">	

		<?php        

        echo CHtml::submitButton('Ver cliente', array('submit'=>array('/clientes/admin')));

		

    ?>

	</div></td>

     <td width="45"><div align="left">

      <?php        

        echo CHtml::submitButton('Cuentas X Cobrar', array('submit'=>array('/reportes/CuentasxCobrarC'))); 

    ?>

    </div></td> 

  </table>

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

	'id'=>'prefacturas-form',

	'enableAjaxValidation'=>false,

)); ?>

 <?php echo '<input type="hidden" id="modelid" value="'.$model->nprefac.'"/>'; ?>

    

          <p class="note"><span style="float: left;"><style>

            .rojo1 {background-color: red; }

	  </style>

	</span></p>

	

	<p class="note"><?php echo $form->errorSummary($model); ?></p>


	<table width="375" border="1">

      <tr>

          

        <th width="66" scope="row"><div align="left"><span style="float: left;"> <?php echo $form->labelEx($model,'Fecha'); ?>

        <?php $feriados="['25/12/2017','01/01/2014','02/01/2014', '01/05/2014','25/07/2014','26/07/2014','27/07/2014','10/10/2014','25/12/2014','01/01/2015','02/01/2015', '01/05/2015','25/07/2015','26/07/2015','27/07/2015','10/10/2015','25/12/2015','01/01/2016','02/01/2016', '01/05/2016','25/07/2016','26/07/2016','27/07/2016','10/10/2016','25/12/2016']";   

		$this->widget('CJuiDatePickerEvents', array(

                    'model'=>$model,

                    'attribute'=>'fecha',

                    'value'=>$model->fecha,

		    'htmlOptions' => array('readonly'=>"readonly"),

                    'language' => 'es',

                    'events'=> array("beforeShowDay"=>"function(date) {var events = $feriados ;

                        var current='';

                        // agrego el cero a izq si corresponde

                        if (date.getDate()<10)

                                current='0'+date.getDate()+'/';

                        else

                                current=date.getDate()+'/';

                        if (date.getMonth() + 1<10)

                                current=current+'0'+(date.getMonth()+1)+'/';

                        else

                                current=current+(date.getMonth()+1)+'/';

                        current=current+date.getFullYear();

                        

                        //feriados s&aacute;bados y domingos

                        return (jQuery.inArray(current, events) == -1 && date.getDay()!=0 && date.getDay()!=7)?[true, '']:[true,'rojo1','D&iacute;a no laborable'];},"),

                    'options'=>array(

                        'defaultDate'=>$model->fecha,

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

                        'showAnim'=>'slide',

						//'minDate'=>'date-30("d-m-Y")', //fecha minima

						'maxDate'=> "+20Y", //fecha maxima

						

			      ),

       		)); ?>

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

        <td width="66"><span class="row"><?php echo $form->labelEx($model,'nprefac'); ?> <?php echo $form->textField($model,'nprefac'); ?> <?php echo $form->error($model,'nprefac'); ?> </span></td>

        <td width="73"><div align="left"><?php echo $form->labelEx($model,'Tipo Salida'); ?><?php echo $form->dropDownList($model,'Codsalida',  

	CHtml::listData(Tiposalida::model()->findAll(array('order'=>'Descripcion')), 'Codsalida', 'Descripcion')); ?><?php echo $form->error($model,'Codsalida'); ?></div></td>

      <td width="66"><div align="left"><?php echo $form->labelEx($model,'Moneda'); ?><?php echo $form->dropDownList($model,'CodMon',  

	CHtml::listData(monedas::model()->findAll(array('order'=>'NMoneda')), 'CodMon', 'NMoneda')); ?><?php echo $form->error($model,'CodMon');?> </div></td>

     <td width="70"><div align="left"><?php echo $form->labelEx($model,'Cliente'); ?><span class="row"><?php echo $form->dropDownList($model,'CodCliente',  

	CHtml::listData(Clientes::model()->findAll(array('order'=>'Descripcion')), 'CodCliente', 'Descripcion'),

	array(                              

			'ajax' => array(

			'type'=>'POST',

			'url'=>CController::createUrl('Prefacturas/actualizarFirmantes'),

			'dataType'=>'json',

			'data'=>array('idCodigo'=>'js:this.value'),

			'success'=>'function(data) {

				$("#Prefacturas_CI").html(data.firmantes); 

			}') 

	)

	); ?> <?php echo $form->error($model,'CodCliente'); ?></span></div></td>

      </tr>

</table>

<table width="375" border="1">

  <tr>

    <td width="43"><?php echo $form->labelEx($model,'Firma Autorizada'); ?><?php echo $form->dropDownList($model,'CI',

    array()); ?><?php echo $form->error($model,'CI'); ?></td>

	<td width="52">&nbsp;</td>

   <td width="70"><div align="left"><?php echo $form->labelEx($model,'Entidad o UEB'); ?><span class="row"><?php echo $form->dropDownList($model,'CodUEB',  

	CHtml::listData(Entidades::model()->findAll(array('order'=>'NEnt')), 'CodUEB', 'NEnt'),

	array(                              

			'ajax' => array(

			'type'=>'POST',

			'url'=>CController::createUrl('Prefacturas/actualizarPuntoventas'),

			'dataType'=>'json',

			'data'=>array('idCod'=>'js:this.value'),

			'success'=>'function(data) {

			$("#Prefacturas_CodPVen").html(data.puntoventas); 

			}') 

	)

	); ?> <?php echo $form->error($model,'CodUEB'); ?></span></div></td>

    <td width="43"><?php echo $form->labelEx($model,'Punto Venta'); ?><?php echo $form->dropDownList($model,'CodPVen',

    array()); ?><?php echo $form->error($model,'CodPVen'); ?></td>	

   <td width="54">&nbsp;</td>

    <td width="9">&nbsp;</td>

    <td width="52">&nbsp;</td>

	<td width="52">&nbsp;</td>

	<td width="52">&nbsp;</td>

	<td width="52">&nbsp;</td>

  </tr>

</table>

<!-- ---------------------------------------- Detalles de la Factura ------------------------------------- -->

        <fieldset>

		<legend>Lista de Productos</legend>

		<table>

        <tr>                             

                <td>

                    <label>Producto</label>

                    <?php 

                        $conceptos=array();

                        $todos=Productos::model()->findAll(array('order'=>'NProductos'));

                        $pre=Preciomn::model()->findAll(array('order'=>'Descripcion'));

                     

                        foreach ($todos as $producto) {

                            $esta=false;

                            foreach ($model->detallePrefac as $value) {

                                if($producto->NProductos==$value->idProducto->NProductos){

                                        $esta=true;

                                        break;

                                }                                                    

                             }

                             if(!$esta)

                                 $conceptos[$producto->Codprod]=$producto->NProductos;

                        }

                                          echo CHtml::dropDownList('producto','', $conceptos,array(                                        

                                                    'onChange'=>'javascript:ActualizarCodigo()',										 

                                                ));  

                            

                        ?>

                </td>   

               <td>

                        <label>Código</label>

                        <input type="text" id="incodigo"/>

                </td>

            

                <td>

                        <label>Cantidad</label>

                        <input type="text" id="incantidad"/>

                </td>

                      <tr>

                <td>

                        <label>Código Precio MN</label>

                        <input type="text" id="inprecio"/>

                </td>

                <td>

                        <label>Código Descuento</label>

                        <input type="text" id="indescuento"/>

                </td>

              

                <td>

                        <label>Código Recargo</label>

                        <input type="text" id="inrecargo"/>

                </td>

                 </tr> 

                

          </tr>

        <tr>

                <td>

                        <input type="button" id="btnAdd" value="Adicionar Producto"/>

                </td>

        </tr>

</table>

		

    <table id="tblData" class="mystyle">         

        <thead>

            <tr>  

                <th>Código</th>

                <th>Producto</th>

                <th>Cantidad</th>

                <th>Precio MN</th>

                <th>Descuento</th>

                <th>Recargo</th>

                <th style="width:50px"></th>

            </tr>

        </thead>

        <tbody>

            <?php 

                foreach ($model->detallePrefac as $value) {

                    echo "<tr>";

                    echo "<td>".$value->idProducto->Codprod."</td>";

                    echo "<td>".$value->idProducto->NProductos."</td>";

                    echo "<td>".$value->cantidad."</td>";                            

                   echo "<td>".$value->Cosdes."</td>";

                    echo "<td>".$value->Codpre."</td>";

                    echo "<td>".$value->Codrec."</td>";

                   echo "<td><img src='".Yii::app()->request->baseUrl."/images/update.png' class='btnEdit' title='Actualizar' style='cursor:pointer'>

                             <img src='".Yii::app()->request->baseUrl."/images/delete.png' class='btnDelete' title='Eliminar' style='cursor:pointer'/></td>";

                    echo "</tr>";

                 }

            ?>  

        </tbody>

    </table>

           

	

</fieldset>

	<div class="row buttons">

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

	</div>


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




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



Disculpen halla puesto toda mi forma, es para que vean donde puedo poner una condición para comprobar si existe el numero que no se puede duplicar en es caso [size=2]nprefac[/size][size=2] .[/size]

antes de guardar, en la parte donde recibes los datos has un criteria

en tu controlador …







// luego de recibir los datos


$criteria = new CDbCriteria;

$criteria->AddCondition('tu_campo='.$model->tu_campo); 

$buscar = Tu_Modelo::model()->findAll($criteria);


....

.......

..........


//justo antes de guardar preguntas si buscar es mayor que cero


if ($buscar>=0){

//pones tu alert 


}

else{

//guardas

}









Hola amigo ErickMartinez

Mira como puse el trozo de codigo y no me resulto





public function actionSalvarPrefac() {

        $id=$_POST['modelid'];

       

		if($id)

                $model=$this->loadModel($id);   

        else            

                

				$model = new Prefacturas;   

        

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

        //Lo que se guarda en tabla Prefacturas

              $model->fecha=$_POST['fecha'];

              $model->nprefac=$_POST['nprefac'];

              $model->Codsalida=$_POST['codsalida'];

              $model->CodCliente=$_POST['cliente'];

              $model->CodUEB=$_POST['codueb'];

              $model->CodMon=$_POST['codmon'];

              $model->CI=$_POST['ci'];

              $model->CodPVen=$_POST['codpven'];

   // luego de recibir los datos


            $criteria = new CDbCriteria;

            $criteria->AddCondition('nprefac='.$model->nprefac); 

            $buscar = Prefacturas::model()->findAll($criteria);

}         

          

       if ($model->save()) {

                Detallespre::model()->deleteAll('Id_pre=:nprefac', array(':nprefac'=>$model->nprefac));


        foreach($_POST['detalle'] as $item){

            //Lo que se guarda en tabla Detallespre

            $detalle=new Detallespre;      

            $detalle->Id_pre=$model->nprefac;

            $detalle->Codprod=$item['producto'];

            $detalle->cantidad=$item['cantidad'];

            $detalle->Codpre=$item['precio'];

            $detalle->Cosdes=$item['descuento'];

            $detalle->Codrec=$item['recargo'];

           

 //justo antes de guardar preguntas si buscar es mayor que cero


           if ($buscar>=0){

            alert("No puede guardarla ya que existe ese número de prefactura");


                }

            else{

            $detalle->save();

                   }

              }

         }

    }



, no me tira la alerta y lo que hace entonces que no llena la tabla Detallespre que son los detalles de la prefactura