Actualizar Submayor De Productos

Saludos a todos, una vez necesitando de los útiles consejos de este Forum, el problema es que tengo que actualizar los submayores al dar entrada o salida de un producto, tengo para ello en el caso de las entradas las tablas, datosent con los campos (Fecha, Codprod, Codentrada, CodMon,CodUEB, Cantidad )donde entran los datos de entrada de un producto determinado, una tabla submayorprod donde se actualiza el submayor con los campos (Codprod, CodUEB, saldoaper, SaldoAct) del producto al darle entrada en este caso estan debidamente relacionadas las tablas productos, datosen, submayorprod por el campo Codprod y datosent, UEB y%

El problema es que estas llamando a un modelo que no has importado, es decir que no encuentra el fichero. Busca como importar fichero en el config/main.php que ahora no tengo a mano la información.

Postea el código del modelo “Datosent”. Dónde te falla, al guardar, al rellenar el criteria????

Aquí:




$criteria->condition='Codprod=:codigo';  

$criteria->condition='CodUEB=:coden';                

$criteria->params=array(':codigo'=>$model->Codprod);

$criteria->params=array(':coden'=>$model->CodUEB);



Creo q estás machacando una condición con otra. Tendrías que utilizar addContition() para CodUEB o poner las 2 condiciones en condition. Y en params lo mismo, deberías meterlos todos en un sólo array…

Un saludo.

Cuando inicie este dialogo, no me di cuenta realmente del error y no supe explicar lo que necesitaba, pido mis disculpas, aquí esta como veo ahora el problema:

El problema es que me di cuenta que en la tabla submayorprod debía aparecer los productos para cada UEB o Entidades, para ello en las tablas datosent, datossal y submayorprod adicione el campo CodUEB, relacionadas con ese campo en la tabla Entidades (UEB).

Cuando le de entrada a un producto me debe actualizar la fila correspondiente a ese producto para esa UEB seleccionada, al igual que a la hora de actualizar y borrar un productos, como tengo ahora el código se lo hace al primer producto encontrado para la UEB seleccionada, o sea, si adiciono un producto de código 123.7.01.8413 para la UEB 6, me actualiza el código 123.4.99.000 para la UEB 6.

En el caso de las salidas me actualiza el código del producto seleccionado para la primera UEB localizada, o sea, si le doy salida a los productos 123.4.99.000 y 123.7.01.8413 me actualiza esos códigos en la UEB 1.

para ello envio los siguientes ficheros:

DatossentController:




public function actionCreate()

            	{

              	$model=new Datosent;                      	

           	

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

                	{

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

                    	if($model->save()){   

					   $criteria=new CDbCriteria;                                    	

                                       	$criteria->condition='Codprod=:codigo';  

					   $criteria->condition='CodUEB=:coden';   		

                                       	$criteria->params=array(':codigo'=>$model->Codprod);

                                       	$criteria->params=array(':coden'=>$model->CodUEB);

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

                                       	$objSubmp->SaldoAct = $objSubmp->SaldoAct + $model->Cantidad;

                                       	$objSubmp->save();

                                      	

					   $this->redirect(array('view', 'id' => $model->Id));

                                      	}

                	} 

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

            	'model'=>$model

					));

            	}




	/**

	 * Updates a particular model.

	 * If update is successful, the browser will be redirected to the 'view' page.

	 * @param integer $id the ID of the model to be updated

	 */

	public function actionUpdate($id)

            	{

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

            	

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

                    	{

                    	$cantidad_inicial=$model->Cantidad;

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

                                            	//$cantidadinicial = $model->Cantidad;

                                            	//SaldoAct = salcdo actua;l - cantidad incial

                    	if($model->save()){   

                                    	$criteria=new CDbCriteria;                                       	

                                    	$criteria->condition='Codprod=:codigo';  

										$criteria->condition='CodUEB=:coden';  	

                                    	$criteria->params=array(':codigo'=>$model->Codprod);

										$criteria->params=array(':coden'=>$model->CodUEB);

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

                                    	$objSubmp->SaldoAct = $objSubmp->SaldoAct-$cantidad_inicial+$model->Cantidad;

                                    	$objSubmp->save();

                                    	$this->redirect(array('view', 'id' => $model->Id));

                                    	}

                                                                              	

                    	} 

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

                    	'model'=>$model

                                    	));

    	}


	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

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

		

		$criteria=new CDbCriteria;

		$criteria->condition='Codprod=:codigo';  

		$criteria->condition='CodUEB=:coden';  	

		$criteria->params=array(':codigo'=>$model->Codprod);

		$criteria->params=array(':coden'=>$model->CodUEB);

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

		$objSubmp->SaldoAct = $objSubmp->SaldoAct-$model->Cantidad;

		

            	$objSubmp->save();

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}



DatossalController:




public function actionSalvarFactura()

	{

            	$id=$_POST['modelid'];

        	

            	if($id)

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

            	else        	

                	$model = new Datossal;	

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

		{

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

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

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

			$model->CodProvedor=$_POST['provedor'];

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

			$model->Descuento=$_POST['descuento'];

			$model->DC=$_POST['dc'];

			

                     	if ($model->save()) {

                         	

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

                          	//Actualizar saldo de productos

                            	$criteria=new CDbCriteria;                                    	

                            	$criteria->condition='Codprod=:codigo';

								//$criteria->condition='CodUEB=:coden';  //puesto despues	

                            	$criteria->params=array(':codigo'=>$value->Codprod);

								//$criteria->params=array(':coden'=>$model->CodUEB); //puesto despues

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

                            	$objSubmp->SaldoAct = $objSubmp->SaldoAct + $value->cantidad;

                            	$objSubmp->save();                                                                              	

                         	} 

							 

                        	//Elimino todos los detalles de la Salida

                        	Detallesfact::model()->deleteAll('Id_sal=:id', array(':id'=>$model->Id));

                                           	

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


                           	//Insertar los detalles de la salida

                            	$producto= Productos::model()->find('NProductos=:postID', array(':postID'=>$item['producto']));

                            	$detalle=new Detallesfact;	

                            	$detalle->Id_sal=$model->Id;

                            	$detalle->Codprod=$producto->Codprod;

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

                            	$detalle->save(); 	

                            	

                            	//Actualizar saldo de productos

                            	$criteria=new CDbCriteria;                                    	

                            	$criteria->condition='Codprod=:codigo'; 

								//$criteria->condition='CodUEB=:coden';  //puesto despues		

                            	$criteria->params=array(':codigo'=>$detalle->Codprod);

								//$criteria->params=array(':coden'=>$model->CodUEB); //puesto despues

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

                            	$objSubmp->SaldoAct = $objSubmp->SaldoAct - $detalle->cantidad;

                            	$objSubmp->save();


                        	}	

                    	}

		}		

	}

 	

    	public function actionImprimir($id)

	{

        	

        	spl_autoload_unregister(array('YiiBase','autoload'));

        	require(Yii::app()->basePath.'/extensions/phpexcel/Classes/PHPExcel.php');

        	spl_autoload_register(array('YiiBase', 'autoload'));

        	

        	$objPHPExcel = PHPExcel_IOFactory::load("template.xls");	

        	

        	$objPHPExcel->setActiveSheetIndex(0)			

                                            	->setCellValue('A1', $id);	

                                           	

        	

        	$sql='SELECT  `datossal`.`fecha`,`datossal`.`Codsalida`,`datossal`.`CodCliente`,

                        	`datossal`.`CodProvedor`,`datossal`.`DC`,`datossal`.`CodMon`                        	

                	FROM `datossal`,`productos`                	

                	ORDER BY `datossal`.`fecha`';                	

                                          	

        	$command = Yii::app()->db->createCommand($sql);		

        	$dataReader = $command->queryAll();

        	

        	$indice=3;

        	foreach($dataReader as $row){  

         	

            	$objPHPExcel->setActiveSheetIndex(0)			

                                            	->setCellValue('B'.$indice, $row['fecha']) 

                                            	->setCellValue('C'.$indice, $row['Codsalida']) 

                                            	->setCellValue('D'.$indice, $row['CodCliente']) 

                                            	->setCellValue('E'.$indice, $row['CodProvedor']) 

                                            	->setCellValue('F'.$indice, $row['DC']) 

                                            	->setCellValue('G'.$indice, $row['CodMon']); 

                    	

            	$indice++;    	

             	}

     	

        	header('Content-Type: application/vnd.ms-excel');

        	header('Content-Disposition: attachment;filename="reporte.xls"');

        	header('Cache-Control: max-age=0');


        	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        	$objWriter->save('php://output');	

				

	}



Datosent Model




class Datosent extends CActiveRecord

{

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Datosent the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'datosent';

	}

	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

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

		// will receive user inputs.

		return array(

			array('Codentrada', 'numerical', 'integerOnly'=>true),

			array('Cantidad', 'numerical'),

			array('Codprod', 'length', 'max'=>14),

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

			array('Fecha', 'safe'),

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

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

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

			array('Fecha, Codprod, Codentrada, CodMon, CodUEB,Cantidad, Id', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

		'codentrada' => array(self::BELONGS_TO, 'Tipoentrada', 'Codentrada'),

		'codMon' => array(self::BELONGS_TO, 'Monedas', 'CodMon'),

		'codprod' => array(self::BELONGS_TO, 'productos', 'Codprod'),

		'codUEB' => array(self::BELONGS_TO, 'Entidades', 'CodUEB'),

		'codprod' => array(self::BELONGS_TO, 'submayorprod', 'Codprod'),

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'Fecha' => 'Fecha',

			'Codprod' => 'Codprod',

			'Codentrada' => 'Codentrada',

			'CodMon'=> 'CodMon',

        	'CodUEB'=> 'CodUEB',

			'Cantidad' => 'Cantidad',

			);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.


		$criteria=new CDbCriteria;

		$criteria->compare('Fecha',$this->Fecha,true);

		$criteria->compare('Codprod',$this->Codprod,true);

		$criteria->compare('Codentrada',$this->Codentrada);

		$criteria->compare('CodMon',$this->CodMon);

    	$criteria->compare('CodUEB',$this->CodUEB);

		$criteria->compare('Cantidad',$this->Cantidad);

		

		return new CActiveDataProvider($this, array(

	  	'criteria'=>$criteria,

		));

	}

}



Datossal Model




class Datossal extends CActiveRecord

{

	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'datossal';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

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

		// will receive user inputs.

		return array(

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

			array('DC', 'numerical'),

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

			array('CodProvedor, CodUEB', 'length', 'max'=>12),

			array('Descuento', 'length', 'max'=>2),

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

			array('fecha', 'safe'),

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

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

			array('Id, fecha, Codsalida, CodCliente, CodProvedor, CodMon, Descuento, DC, CodUEB, Id_Fir', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'codsalida' => array(self::BELONGS_TO, 'Tiposalida', 'Codsalida'),

			'codCliente' => array(self::BELONGS_TO, 'Clientes', 'CodCliente'),

			'idFir' => array(self::BELONGS_TO, 'Firmantes', 'Id_Fir'),

			'codMon' => array(self::BELONGS_TO, 'Monedas', 'CodMon'),

			'codProvedor' => array(self::BELONGS_TO, 'Proveedor', 'CodProvedor'),

			'codUEB' => array(self::BELONGS_TO, 'Entidades', 'CodUEB'),

			'detalleFacturas' => array(self::HAS_MANY, 'Detallesfact', 'Id_sal'),

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'Id' => 'ID',

			'fecha' => 'Fecha',

			'Codsalida' => 'Codsalida',

			'CodCliente' => 'Cod Cliente',

			'CodProvedor' => 'Cod Provedor',

			'CodMon' => 'Cod Mon',

			'Descuento' => 'Descuento',

			'DC' => 'Dc',

			'CodUEB' => 'CodUEB',

			'Id_Fir' => 'Id Fir',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 *

	 * Typical usecase:

	 * - Initialize the model fields with values from filter form.

	 * - Execute this method to get CActiveDataProvider instance which will filter

	 * models according to data in model fields.

	 * - Pass data provider to CGridView, CListView or any similar widget.

	 *

	 * @return CActiveDataProvider the data provider that can return the models

	 * based on the search/filter conditions.

	 */

	public function search()

	{

		// @todo Please modify the following code to remove attributes that should not be searched.


		$criteria=new CDbCriteria;


		$criteria->compare('Id',$this->Id);

		$criteria->compare('fecha',$this->fecha,true);

		$criteria->compare('Codsalida',$this->Codsalida);

		$criteria->compare('CodCliente',$this->CodCliente,true);

		$criteria->compare('CodProvedor',$this->CodProvedor,true);

		$criteria->compare('CodMon',$this->CodMon);

		$criteria->compare('Descuento',$this->Descuento,true);

		$criteria->compare('DC',$this->DC);

		$criteria->compare('CodUEB',$this->CodUEB,true);

		$criteria->compare('Id_Fir',$this->Id_Fir,true);


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}


	/**

	 * Returns the static model of the specified AR class.

	 * Please note that you should have this exact method in all your CActiveRecord descendants!

	 * @param string $className active record class name.

	 * @return Datossal the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}

}



Un saludo.

[/quote]

Has probado a hacer lo q te dije?

Si resolví de la siguiente forma, según me dijiste muchas gracias, ahora el problema lo tengo en las salidas, te voy a enviar donde hago esto en las salidas para ver si también me ayudas.




public function actionCreate()

            	{

              	$model=new Datosent;                      	

   			

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

                	{

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

                    	if($model->save()){   

	                   $criteria=new CDbCriteria;                                    	

		           	$criteria->addCondition('CodUEB=:coden'); 

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

				       $criteria->params=array(':coden'=>$model->CodUEB , ':codigo'=>$model->Codprod);		

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

				       $objSubmp->SaldoAct = $objSubmp->SaldoAct + $model->Cantidad;

				       $objSubmp->save();

                   					

	                   $this->redirect(array('view', 'id' => $model->Id));

                                      	}

                	} 

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

            	'model'=>$model

					));

            	}



Amigo aqui te envio el controlador de salidas, ya que aquí no trabaja según lo hicimos en entradas, en este caso lo hago el la acción actionSalvarFactura, ya que tengo una tabla datossal y otra tabla detallesfact.




<?php


class DatossalController extends Controller

{

	/**

 	* @var string the default layout for the views. Defaults to '//layouts/column2', meaning

 	* using two-column layout. See 'protected/views/layouts/column2.php'.

 	*/

	public $layout='//layouts/column2';


	/**

 	* @return array action filters

 	*/

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

			'postOnly + delete', // we only allow deletion via POST request

		);

	}


	/**

 	* Specifies the access control rules.

 	* This method is used by the 'accessControl' filter.

 	* @return array access control rules

 	*/

	public function accessRules()

	{

		return array(

			array('allow',  // allow all users to perform 'index' and 'view' actions

				'actions'=>array('index','view'),

				'users'=>array('*'),

			),

			array('allow', // allow authenticated user to perform 'create' and 'update' actions

				'actions'=>array('create','update','salvarFactura','imprimir','Imprimirexis'),

				'users'=>array('@'),

			),

			array('allow', // allow admin user to perform 'admin' and 'delete' actions

				'actions'=>array('admin','delete'),

				'users'=>array('admin'),

			),

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

 	* Displays a particular model.

 	* @param integer $id the ID of the model to be displayed

 	*/

	public function actionView($id)

	{

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

			'model'=>$this->loadModel($id),

		));

	}

public function actionSalvarFactura()

	{

            	$id=$_POST['modelid'];

        	

            	if($id)

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

            	else        	

                	$model = new Datossal;	

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

		{

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

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

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

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

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

	  					

  			if ($model->save()) {

  			

			//   Detallesfact::model()->deleteAll('Id_sal=:id', array(':id'=>$model->Id));

           	

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

			//  $producto= Productos::model()->find('NProductos=:postID', array(':postID'=>$item['producto']));

			  				//Actualizar saldo de productos

	     	$criteria=new CDbCriteria; 

	     	$criteria->addCondition('CodUEB=:coden'); 

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

	     	$criteria->params=array(':coden'=>$model->CodUEB , ':codigo'=>$model->Codprod);		

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

	     	$objSubmp->SaldoAct = $objSubmp->SaldoAct + $value->cantidad;

	     	$objSubmp->save();                                                                              	

                        	} 

			                 

    	//Elimino todos los detalles de la Salida

   	Detallesfact::model()->deleteAll('Id_sal=:id', array(':id'=>$model->Id));

                         					

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

			

    	//Insertar los detalles de la salida

 		$producto= Productos::model()->find('NProductos=:postID', array(':postID'=>$item['producto']));

 		$detalle=new Detallesfact;	

    	$detalle->Id_sal=$model->Id;

    	$detalle->Codprod=$producto->Codprod;

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

    	$detalle->save(); 	

										

    	//actualizar saldo de productos

    	$criteria=new CDbCriteria;                                    	

    	$criteria->addCondition('CodUEB=:coden'); 

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

		$criteria->params=array(':codigo'=>$detalle->Codprod);

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

    	$objSubmp->SaldoAct = $objSubmp->SaldoAct - $detalle->cantidad;

    	$objSubmp->save();


                        	}	

                    	}

		}		

	}

 	

	public function actionImprimir($id)

	{

        	spl_autoload_unregister(array('YiiBase','autoload'));

        	require(Yii::app()->basePath.'/extensions/phpexcel/Classes/PHPExcel.php');

        	spl_autoload_register(array('YiiBase', 'autoload'));

        	

        	$objPHPExcel = PHPExcel_IOFactory::load("facturas.xls");	

        	

        	$objPHPExcel->setActiveSheetIndex(0)			

 					->setCellValue('A21', $id);	

                           					

        	

        	$sql='SELECT DISTINCT

  				`proveedor`.`CodREEUP` AS `Codigo Pro`,

  				`proveedor`.`Descripcion` AS `Nombre pro`,

  				`proveedor`.`Direccion` AS `Direccion pro`,

  				`proveedor`.`Telefono`,

  				`proveedor`.`NIT` AS `NIT PRO`,

  				`proveedor`.`NRegCom` AS `Reg Com Pro`,

  				`proveedor`.`NRegMer` AS `Reg Mer pro`,

  				`proveedor`.`CuentaCUC` AS `CuentaCUC pro`,

  				`proveedor`.`CuentaMN` AS `CuentaMNPro`,

  				`clientes`.`CodCliente` AS `Codigo Cliente`,

  				`clientes`.`Descripcion` AS `Nombre Cliente`,

  				`clientes`.`Direccion` AS `Direccion Cliente`,

  				`clientes`.`NIT` AS `NIT Cliente`,

  				`clientes`.`NRegCom` AS `RegCom  Cliente`,

  				`clientes`.`NRegMer` AS `RegMer  Cliente`,

  				`clientes`.`CuentaCUP` AS `CuentaCUP Cliente`,

  				`clientes`.`CuentaCUC` AS `CuentaCUC Cliente`,

  				`clientes`.`NoContrato` AS `NoContrato Cliente`,

  				`datossal`.`fecha`,

  				`productos`.`NProductos`,

  				`productos`.`PrecioMay`,

  				`productos`.`PrecioMinli`,

  				`productos`.`PrecioMinCan`,

  				`detallesfact`.`Cantidad`,

  				`detallesfact`.`Codprod`,

  				`productos`.`UM`,

  				`detallesfact`.`Id_sal`

			FROM

				`clientes`

  				INNER JOIN `datossal` ON (`clientes`.`CodCliente` = `datossal`.`CodCliente`)

  				INNER JOIN `detallesfact` ON (`datossal`.`Id` = `detallesfact`.`Id_sal`)

  				INNER JOIN `productos` ON (`detallesfact`.`Codprod` = `productos`.`Codprod`),

  				`proveedor`,

  				`filtro`

			WHERE

  				`clientes`.`CodCliente` = `datossal`.`CodCliente` AND

  				`productos`.`Codprod` = `detallesfact`.`Codprod` AND

  				(`datossal`.`Codsalida` = 1 OR

  				`datossal`.`Codsalida` = 2) AND

  				`filtro`.`NFact` = `detallesfact`.`Id_sal`

			ORDER BY

					`Nombre pro`';                	

                                          	

        	$command = Yii::app()->db->createCommand($sql);		

        	$dataReader = $command->queryAll();

        	

        	$indnom=21;

			$indcan=21;

			$indpmn=21;

			$indpcuc=21;

			$indpcod=21;

			$indpum=21;

        	foreach($dataReader as $row){  

 			

            	$objPHPExcel->setActiveSheetIndex(0)

            				->setCellValue('C2', $row['Nombre pro']) 

                        	->setCellValue('C3', $row['Direccion pro']) 

                        	->setCellValue('H2', $row['Codigo Pro']) 

                        	->setCellValue('E4', $row['Telefono']) 

                        	->setCellValue('E5', $row['NIT PRO']) 

                        	->setCellValue('F6', $row['Reg Com Pro'])

							->setCellValue('D7', $row['CuentaMNPro']) 

							->setCellValue('D8', $row['CuentaCUC pro']) 

							->setCellValue('G7', $row['Nombre pro']) 

							->setCellValue('C10', $row['Nombre Cliente'])

							->setCellValue('C11', $row['Direccion Cliente']) 	

							->setCellValue('E12', $row['NIT Cliente'])

							->setCellValue('H10', $row['Codigo Cliente'])

							->setCellValue('E13', $row['RegCom  Cliente'])

							->setCellValue('D14', $row['CuentaCUP Cliente'])

							->setCellValue('I14', $row['CuentaCUC Cliente'])

							->setCellValue('D17', $row['NoContrato Cliente'])

							->setCellValue('C'.$indnom, $row['NProductos'])

							->setCellValue('G'.$indcan, $row['Cantidad'])

							->setCellValue('H'.$indpmn, $row['PrecioMay'])

							->setCellValue('A'.$indpcod, $row['Codprod'])

							->setCellValue('F'.$indpcod, $row['UM'])

							->setCellValue('I'.$indpcod, $row['PrecioMinli']);	

           	

 			$indnom++; 

         	$indcan++;

         	$indpmn++;

         	$indpcuc++;

         	$indpcod++;

         	$indpum++;

 				

 				}

        	header('Content-Type: application/vnd.ms-excel');

        	header('Content-Disposition: attachment;filename="facturas.xls"');

        	header('Cache-Control: max-age=0');


        	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        	$objWriter->save('php://output');

		}

// reporte de existencias por UEB		

	public function actionImprimirexis($id)

	{			

			spl_autoload_unregister(array('YiiBase','autoload'));

        	require(Yii::app()->basePath.'/extensions/phpexcel/Classes/PHPExcel.php');

        	spl_autoload_register(array('YiiBase', 'autoload'));

        	

        	$objPHPExcel = PHPExcel_IOFactory::load("ExistenciasUEB.xls");	

        	

        	$objPHPExcel->setActiveSheetIndex(0)			

 					->setCellValue('A5', $id);	

                           					

        	

			$sql='SELECT 

  				`proveedor`.`CodREEUP` AS `Codigo`,

  				`proveedor`.`Descripcion`,

  				`entidades`.`NEnt`,

  				`submayorprod`.`Codprod`,

  				`productos`.`NProductos` AS `Productos`,

  				`submayorprod`.`SaldoAct` AS `Existencia`,

  				`productos`.`UM`,

  				`productos`.`PrecioMay`,

  				`productos`.`PrecioMinli`,

  				`productos`.`PrecioMinCan`

				FROM

  				`submayorprod`

  				INNER JOIN `productos` ON (`submayorprod`.`Codprod` = `productos`.`Codprod`)

  				INNER JOIN `entidades` ON (`submayorprod`.`CodUEB` = `entidades`.`CodUEB`),

  				`proveedor`

				WHERE

  				`submayorprod`.`SaldoAct` > 0

				GROUP BY

  				productos.NProductos,

  				entidades.NEnt

				ORDER BY

  				`NEnt`,

  				`Productos`';                	

                                          	

        	$command = Yii::app()->db->createCommand($sql);		

        	$dataReader = $command->queryAll();

        	

        	$indice=5;

			foreach($dataReader as $row){  

 			

            	$objPHPExcel->setActiveSheetIndex(0)

							->setCellValue('B1', $row['Descripcion']) 

							->setCellValue('B2', $row['Codigo'])

            				->setCellValue('A'.$indice, $row['NEnt'])

							->setCellValue('B'.$indice, $row['Codprod'])

							->setCellValue('C'.$indice, $row['Productos'])

							->setCellValue('D'.$indice, $row['UM'])

							->setCellValue('E'.$indice, $row['Existencia'])

							->setCellValue('F'.$indice, $row['PrecioMay'])	

							->setCellValue('G'.$indice, $row['PrecioMinli']);		

                  				

 			$indice++; 

                 		

 				}

        	header('Content-Type: application/vnd.ms-excel');

        	header('Content-Disposition: attachment;filename="ExistenciasUEB.xls"');

        	header('Cache-Control: max-age=0');


        	$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');

        	$objWriter->save('php://output');

		//	

	}

	/**

 	* Creates a new model.

 	* If creation is successful, the browser will be redirected to the 'view' page.

 	*/

	public function actionCreate()

	{

		$model=new Datossal;


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->Id));

		}


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

			'model'=>$model,

		));

	}


	/**

 	* Updates a particular model.

 	* If update is successful, the browser will be redirected to the 'view' page.

 	* @param integer $id the ID of the model to be updated

 	*/

	public function actionUpdate($id)

	{

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


		// Uncomment the following line if AJAX validation is needed

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


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

		{

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

			if($model->save())

				$this->redirect(array('view','id'=>$model->Id));

		}


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

			'model'=>$model,

		));

	}


	/**

 	* Deletes a particular model.

 	* If deletion is successful, the browser will be redirected to the 'admin' page.

 	* @param integer $id the ID of the model to be deleted

 	*/

	public function actionDelete($id)

	{

		$this->loadModel($id)->delete();


		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

		if(!isset($_GET['ajax']))

			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));

	}


	/**

 	* Lists all models.

 	*/

	public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Datossal');

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

			'dataProvider'=>$dataProvider,

		));

	}


	/**

 	* Manages all models.

 	*/

	public function actionAdmin()

	{

		$model=new Datossal('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Datossal']))

			$model->attributes=$_GET['Datossal'];


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

			'model'=>$model,

		));

	}


	/**

 	* Returns the data model based on the primary key given in the GET variable.

 	* If the data model is not found, an HTTP exception will be raised.

 	* @param integer $id the ID of the model to be loaded

 	* @return Datossal the loaded model

 	* @throws CHttpException

 	*/

	public function loadModel($id)

	{

		$model=Datossal::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

 	* Performs the AJAX validation.

 	* @param Datossal $model the model to be validated

 	*/

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='datossal-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

}



Buenos días.

Me alegro de q te funcionase.

Q es lo q te falla de facturas? la actualización del saldo de productos? de que forma te falla?

Además, este trozo de código:




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

                        

        //Insertar los detalles de la salida

                $producto= Productos::model()->find('NProductos=:postID', array(':postID'=>$item['producto']));

                $detalle=new Detallesfact;      

        $detalle->Id_sal=$model->Id;

        $detalle->Codprod=$producto->Codprod;

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

        $detalle->save(); 



En mi opinión lo deberías de cambiar por este:




$detalle=new Detallesfact;   


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

                        

        //Insertar los detalles de la salida

$detalle->isNewRecord = true;   // Esta línea indica q será un nuevo registro.  

        $detalle->Id_sal=$model->Id;

        $detalle->Codprod=Productos::model()->find('NProductos=:postID', array(':postID'=>$item['producto']))->queryScalar();

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

        $detalle->save(); 



De esta forma sólo creas 1 objeto, q será $detalle. De la otra forma estás creando tantos objetos como el número de veces q se ejecuta multiplicado por 2.

Y tambien creo q deberías de utilizar transacciones para las operaciones q realizas.

Un saludo.

Hola chicos, tengo un problema. Estoy tratando de guardar la información de factura de compras,

las tablas son: compra, detallecompra y productos. Para el detalle de compra estoy usando MultiModelForm.

Mi problema es que no está actualizando la CanExistencia, he probado con diferentes forma de realizar update pero esto ha sido en vano. Por favor me podrían ayudar? de antemano muchisimas gracias.

CompraController.php

public function actionCreate()

{      


        Yii::import('ext.multimodelform.MultiModelForm');


        &#036;model = new Compra();


        &#036;member = new Detallecompra();


        &#036;producto=new Productos();


        &#036;proveedor=new Proveedor();


        &#036;validatedMembers = array();  //ensure an empty array





        if(isset(&#036;_POST['Compra']))


        {


            &#036;model-&gt;attributes=&#036;_POST['Compra'];





            if(


                MultiModelForm::validate(&#036;member,&#036;validatedMembers,&#036;deleteItems) &amp;&amp;


                &#036;model-&gt;save())


               {


                    &#036;masterValues = array ('NumCompra'=&gt;&#036;model-&gt;NumCompra);


                if 


                     (MultiModelForm::save(&#036;member,&#036;validatedMembers,&#036;deleteMembers,&#036;masterValues)){

// $this->redirect(array(‘view’,‘id’=>$model->Id));

                 }


                }                  


                &#036;criteria=new CDbCriteria;    


                &#036;criteria-&gt;addCondition('CodProducto=:CodProducto');


                &#036;criteria-&gt;params=array(':CodProducto'=&gt;&#036;member-&gt;CodProducto);      


                if (&#036;criteria&#33;==NULL){

// echo $criteria;

                }


                else {


                    &#036;objProducto-&gt;CanExistencia = &#036;objProducto-&gt;CanExistencia + &#036;member-&gt;Cantidad;


                    &#036;objProducto-&gt;save();


                }


                


        }





        &#036;this-&gt;render('create',array(


            'model'=&gt;&#036;model,


            //submit the member and validatedItems to the widget in the edit form


            'member'=&gt;&#036;member,


            'producto'=&gt;&#036;producto,


            'proveedor'=&gt;&#036;proveedor,


            'validatedMembers' =&gt; &#036;validatedMembers,


        ));


}

Compra.php -Model-

public function relations()

{


	// NOTE: you may need to adjust the relation name and the related


	// class name for the relations automatically generated below.


	return array(


                'detallecompras' =&gt; array(self::HAS_MANY, 'Detallecompra', 'NumCompra'),

// ‘Detalle’ => array(self::HAS_MANY, ‘Detallecompra’, ‘NumCompra’),

	);


}

Detallecompra.php -Model-

public function relations()

{


	// NOTE: you may need to adjust the relation name and the related


	// class name for the relations automatically generated below.


	return array(


                'NumCompra' =&gt; array(self::BELONGS_TO, 'Compra', 'NumCompra'),


                'Compras' =&gt; array(self::HAS_MANY, 'compra', 'NumCompra'),


                'productos'=&gt;array(self::HAS_MANY,'Productos','CodProducto'),


	);


}